RISK IT

[TIL14_23.1.22.] [Node] Express - 'westagram' 게시글 수정, 게시글 지우기, 좋아요 누르기 본문

IT/TIL

[TIL14_23.1.22.] [Node] Express - 'westagram' 게시글 수정, 게시글 지우기, 좋아요 누르기

nomoremystery 2023. 1. 23. 16:25
반응형

작업 내용

  • 게시글 수정하기
  • 게시글 지우기
  • 좋아요 누르기

전체 소스코드

require('dotenv').config();

const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const { DataSource } = require('typeorm');

const mysqlDataSource = new DataSource({
  type: process.env.TYPEORM_CONNECTION,
  host: process.env.TYPEORM_HOST,
  port: process.env.TYPEORM_PORT,
  username: process.env.TYPEORM_USERNAME,
  password: process.env.TYPEORM_PASSWORD,
  database: process.env.TYPEORM_DATABASE,
});

mysqlDataSource
  .initialize()
  .then(() => {
    console.log('Data Source has been initialized!');
  })
  .catch((err) => {
    console.error('Error during Data Source initialization', err);
    mysqlDataSource.destroy();
  });

const app = express();

app.use(cors());
app.use(morgan('dev'));
app.use(express.json());

// health check
app.get('/ping', (req, res) => {
  res.status(200).json({ message: 'pong' });
});

app.post('/users/signup', async (req, res) => {
  const { name, email, password, profileImage } = req.body;

  await mysqlDataSource.query(
    `INSERT INTO users (
      name, 
      email, 
      password, 
      profile_image
    )
      VALUES (
        ?, 
        ?, 
        ?, 
        ?
        );
    `,
    [name, email, password, profileImage]
  );

  res.status(201).json({ message: 'userCreated' });
});

app.post('/posts/users', async (req, res) => {
  const { title, content, postImgUrl, userId } = req.body;

  await mysqlDataSource.query(
    `INSERT INTO posts (
      title,
      content,
      post_image_url,
      user_id
      )
      VALUES (
        ?,
        ?,
        ?,
        ?
        );
        `,
    [title, content, postImgUrl, userId]
  );

  res.status(201).json({ message: 'postCreated' });
});

app.get('/lookup', async (req, res) => {
  await mysqlDataSource.query(
    `SELECT
      u.id AS userId,
      u.profile_image AS userProfileImage,
      p.id AS postingId,
      p.post_image_url AS postingImageUrl,
      p.content AS postingContent
    FROM posts p
    INNER JOIN users u ON u.id = p.user_id;
    `,
    (err, data) => {
      res.status(200).json({ data });
    }
  );
});

app.get('/users/lookup', async (req, res) => {
  await mysqlDataSource.query(
    `SELECT
    u.id AS userId,
    u.profile_image AS userProfileImage,
    JSON_ARRAYAGG(postings_json.posting_id) AS postings
    FROM users u
    INNER JOIN (
    SELECT
    p.id,
    JSON_OBJECT(
      "postingId", id,
      "postingImageUrl", post_image_url,
      "postingContent", content
      ) AS posting_id
      FROM posts p
    ) postings_json
    WHERE u.id=1;
    `,
    (err, data) => {
      res.status(200).json({ data });
    }
  );
});

app.patch('/posts/update/:userId/:postId', async (req, res) => {
  const { userId, postId } = req.params;
  const { content } = req.body;
  await mysqlDataSource.query(
    `UPDATE 
      posts
    SET
      content = ?
    WHERE 
      user_id = ${userId} AND id = ${postId}
    `,
    [content]
  );

  await mysqlDataSource.query(
    `SELECT
      u.id AS userId,
      u.profile_image AS userProfileImage,
      p.id AS postingId,
      p.post_image_url AS postingImageUrl,
      p.content AS postingContent
    FROM posts p
    INNER JOIN users u ON u.id = p.user_id
    WHERE u.id=${userId} AND p.id=${postId}
    `,
    (err, data) => {
      res.status(201).json({ data });
    }
  );
});

app.delete('/posts/delete/:postId', async (req, res) => {
  const { postId } = req.params;

  await mysqlDataSource.query(
    `DELETE 
    FROM posts
    WHERE posts.id = ${postId}
    `
  );
  res.status(200).json({ message: 'postingDeleted' });
});

app.post('/likes/:userId/:postId', async (req, res) => {
  const { userId, postId } = req.params;

  await mysqlDataSource.query(
    `INSERT INTO likes (
      user_id,
      post_id
    )
      VALUES (
        ?, 
        ?
        );
    `,
    [userId, postId]
  );

  res.status(201).json({ message: 'likeCreated' });
});

const PORT = process.env.PORT;
const start = async () => {
  try {
    app.listen(PORT, () => console.log(`Server is listening on ${PORT}!!`));
  } catch (err) {
    console.error(err);
  }
};

start();

추가된 부분

// 게시글 수정하기
app.patch('/posts/update/:userId/:postId', async (req, res) => {
  const { userId, postId } = req.params;
  const { content } = req.body;
  await mysqlDataSource.query(
    `UPDATE 
      posts
    SET
      content = ?
    WHERE 
      user_id = ${userId} AND id = ${postId}
    `,
    [content]
  );

  await mysqlDataSource.query(
    `SELECT
      u.id AS userId,
      u.profile_image AS userProfileImage,
      p.id AS postingId,
      p.post_image_url AS postingImageUrl,
      p.content AS postingContent
    FROM posts p
    INNER JOIN users u ON u.id = p.user_id
    WHERE u.id=${userId} AND p.id=${postId}
    `,
    (err, data) => {
      res.status(201).json({ data });
    }
  );
});

// 게시글 지우기
app.delete('/posts/delete/:postId', async (req, res) => {
  const { postId } = req.params;

  await mysqlDataSource.query(
    `DELETE 
    FROM posts
    WHERE posts.id = ${postId}
    `
  );
  res.status(200).json({ message: 'postingDeleted' });
});

// 좋아요 누르기
app.post('/likes/:userId/:postId', async (req, res) => {
  const { userId, postId } = req.params;

  await mysqlDataSource.query(
    `INSERT INTO likes (
      user_id,
      post_id
    )
      VALUES (
        ?, 
        ?
        );
    `,
    [userId, postId]
  );

  res.status(201).json({ message: 'likeCreated' });
});

req.params를 이용해서 url 주소의 경로를 매개변수로 저장.
이를 활용해서 특정 id에 대한 내용만 쉽게 삭제 할 수 있었다.

반응형