FP7: controllers/posts
76269 단어 ControllerJWTSequelizeController
- Json Web Token
- Sequelize
// 'index.js' from 'controllers/posts' Directory
module.exports = {
create : require('./create'),
read : require('./read'),
search : require('./search'),
tags : require('./tags'),
update : require('./update'),
remove : require('./remove')
};
// 'create.js' from 'controllers/posts' Directory
const { Post, Tag, Post_Tag } = require('../../models');
const jwt = require('jsonwebtoken');
require('dotenv').config();
module.exports = {
post: async (req, res) => {
if (!req.body.title || !req.body.contents) {
res.status(400).json({
data: null,
message: "insufficient parameters supplied"
});
}
if (!req.headers['authorization']) {
res.status(403).json({
data: null,
message: "invalid access token"
});
}
const accessToken = req.headers['authorization'].split(' ')[1];
jwt.verify(accessToken, process.env.ACCESS_SECRET, async (err, decoded) => {
if (err) {
res.status(401).json({
data: null,
message: "not authorized"
});
}
const newPost = await Post.create({
userId: decoded.id,
imageUrl: req.body.imageUrl,
title: req.body.title,
contents: req.body.contents
});
const {tagNames} = req.body;
tagNames.map(async (tagName) => {
await Tag.findOrCreate({
where: {tagName: tagName}
});
})
const foundTagIds = tagNames.map(async (tagName) => {
const foundTag = await Tag.findOne({
where: {tagName: tagName}
});
return foundTag.id;
});
foundTagIds.map(async (tagId) => {
await Post_Tag.create({
postId: newPost.id,
tagId: tagId
});
})
const {id, userId, title, contents, imageUrl, createdAt, updatedAt} = newPost.dataValues;
res.status(201).json({
postData: {id, userId, title, contents, imageUrl, createdAt, updatedAt},
message: "created ok"
});
});
}
};
// 'read.js' from 'controllers/posts' Directory
const { Post, User } = require('../../models');
const jwt = require('jsonwebtoken');
require('dotenv').config();
module.exports = {
getPosts: async (req, res) => {
const allPosts = await Post.findAll();
const resultPosts = allPosts.map(el => el.dataValues);
const allUsers = await User.findAll();
const resultUsers = allUsers.map(el => {
return el.dataValues;
});
let results = [];
resultPosts.forEach(post => {
resultUsers.forEach(user => {
if(post.userId === user.id) {
results.push({...post, user})
}
})
})
res.status(200).json({
results: results,
postsData: resultPosts,
usersData: resultUsers,
message: "ok"
});
},
getUserPosts: async (req, res) => {
if (!req.headers['authorization']) {
res.status(400).json({
data: null,
message: "insufficient parameters supplied"
});
}
const ACCESS_TOKEN = req.headers['authorization'].split(' ')[1];
const payload = await jwt.verify(ACCESS_TOKEN, process.env.ACCESS_SECRET);
const foundPosts = await Post.findAll({
where: {
userId: payload.id
}
})
if (!foundPosts) {
res.status(404).json({
data: null,
message: "not found posts"
});
} else {
const results = foundPosts.map(el => el.dataValues);
res.status(200).json({
postData: results,
message: "ok"
});
}
},
getPost: async (req, res) => {
if (!req.params.id) {
res.status(400).json({
data: null,
message:"insufficient parameters supplied"
});
}
const foundPost = await Post.findOne({
where: {
id: req.params.id
}
});
const foundUser = await User.findOne({
where: {
id: foundPost.userId
}
})
delete foundUser.dataValues.password;
if (!foundPost) {
res.status(404).json({
data: null,
message: "not found post"
});
} else {
const {id, title, contents, imageUrl, userId, like, createdAt, updatedAt} = foundPost;
res.status(200).json({
postData: { id, title, contents, imageUrl, userId, like, createdAt, updatedAt },
userInfo: foundUser.dataValues,
message: "ok"
});
}
}
};
// 'search.js' from 'controllers/posts' Directory
const { Post, Sequelize } = require('../../models');
const { Op } = require("sequelize");
module.exports = {
get: async (req, res) => {
const {keywords} = req.body;
if (!keywords) {
res.status(400).json({
data: null,
message: "insufficient parameters supplied"
});
}
const allPosts = await Post.findAll({
where: {
[Op.or]: [
{title: {
[Op.like]: `${keywords}%`,
[Op.like]: `%${keywords}%`,
// [Op.like]: `%${keywords}`
}},
{contents: {
[Op.like]: `${keywords}%`,
[Op.like]: `%${keywords}%`,
// [Op.like]: `%${keywords}`
}}
]
}
});
const results = allPosts.map(el => el.dataValues);
res.status(200).json({
postsData: results,
message: "searched ok"
});
}
};
// 'tags.js' from 'controllers/posts' Directory
const { Post, Tag, Post_Tag } = require('../../models');
const jwt = require('jsonwebtoken');
require('dotenv').config();
module.exports = {
get: async (req, res) => {
if (!req.params.id) {
res.status(400).json({
data: null,
message: "insufficient parameters supplied"
});
}
const targetPost = await Post.findOne({
where: {
id: req.params.id
}
});
if (!targetPost) {
res.status(404).json({
data: null,
message: "not found post"
});
}
const foundPostTags = await Post_Tag.findAll({
where: {
postId: req.params.id
}
});
const foundTagIds = foundPostTags.map(async (el) => {
return el.dataValues.tagId;
});
const searchedTags = foundTagIds.map(async (tagId) => {
const foundTag = await Tag.findOne({
where: {id: tagId}
});
return foundTag;
});
const results = searchedTags.map(async (tag) => {
return tag.dataValues.tagName;
});
res.status(200).json({
tagsData: results,
message: "ok"
});
}
};
// 'update.js' from 'controllers/posts' Directory
const { Post, Post_Tag, Tag } = require('../../models');
const jwt = require('jsonwebtoken');
const { Op } = require('sequelize');
require('dotenv').config();
module.exports = {
put: async (req, res) => {
if (!req.body.title || !req.body.contents || !req.params.id) {
res.status(400).json({
data: null,
message: "insufficient parameters supplied"
});
}
if (!req.headers['authorization']) {
res.status(403).json({
data: null,
message: "invalid access token"
});
}
const accessToken = req.headers['authorization'].split(' ')[1];
jwt.verify(accessToken, process.env.ACCESS_SECRET, async(err, decoded) => {
if (err) {
res.status(401).json({
data: null,
message: "not authorized"
});
}
const targetPost = await Post.findOne({
where: {
id: req.params.id
}
});
if (!targetPost) {
res.status(404).json({
data: null,
message: "not found post"
});
}
await Post.update(
{
imageUrl: req.body.imageUrl,
title: req.body.title,
contents: req.body.contents
},
{
where: {
id: req.params.id
}
}
);
const updatedPost = await Post.findOne({
where: {id: req.params.id}
});
const {tagNames} = req.body;
tagNames.map(async(tagName) => {
await Tag.findOrCreate({
where: {tagName: tagName}
});
});
const foundTagIds = tagNames.map(async (tagName) => {
const foundTag = await Tag.findOne({
where: {tagName: tagName}
});
return foundTag.id;
});
foundTagIds.map(async (tagId) => {
await Post_Tag.findOrCreate({
where: {
tagId: tagId
}
});
});
const {id, userId, title, contents, imageUrl, createdAt, updatedAt} = updatedPost.dataValues;
res.status(200).json({
postData: { id, userId, title, contents, imageUrl, createdAt, updatedAt },
message: "updated ok"
});
});
}
};
// 'remove.js' from 'controllers/posts' Directory
const { Post } = require('../../models');
const jwt = require('jsonwebtoken');
require('dotenv').config();
module.exports = {
delete: async(req, res) => {
if (!req.params.id) {
res.status(400).json({
data: null,
message: "insufficient parameters supplied"
});
}
if (!req.headers['authorization']) {
res.status(403).json({
data: null,
message: "invalid access token"
});
}
const accessToken = req.headers['authorization'].split(' ')[1];
jwt.verify(accessToken, process.env.ACCESS_SECRET, async(err, decoded) => {
if (err) {
res.status(401).json({
data: null,
message: "not authorized"
});
}
const targetPost = await Post.findOne({
where: {
userId: decoded.id,
id: req.params.id
}
});
if (!targetPost) {
res.status(404).json({
data: null,
message: "not found post"
});
}
await Post.destroy({
where: {
userId: decoded.id,
id: req.params.id
}
});
res.status(200).json({
data: null,
message: "removed ok"
});
});
}
};
Author And Source
이 문제에 관하여(FP7: controllers/posts), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@charlie-lyc/FP7-controllersposts저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)