FP7: controllers/posts

Charlie·2021년 1월 10일
0

First Project

목록 보기
7/8
post-thumbnail
  • 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" 
      });
    });
  }

};

0개의 댓글