RISK IT

[TIL13_23.1.21.] [Node] Express - 'westagram' 게시글 등록, 전체 게시글 조회, 특정 게시글 조회 코드 작성 본문

IT/TIL

[TIL13_23.1.21.] [Node] Express - 'westagram' 게시글 등록, 전체 게시글 조회, 특정 게시글 조회 코드 작성

nomoremystery 2023. 1. 21. 15:00
반응형

작업 내용

  1. 게시글 생성
  2. 게시글 조회
  3. 특정 유저의 게시글 조회

전체 소스코드

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('/users/post', 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.manager.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
    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.manager.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 });
    }
  );
});

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.get('/lookup', async (req, res) => {
  await mysqlDataSource.manager.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
    JOIN users u ON u.id = p.user_id;
    `,
    (err, data) => {
      res.status(200).json({ data });
    }
  );
});
await mysqlDataSource.manager.query();

manager - EntityManagerentity와 함께 처리된다.

  • entity: 실재, 객체라는 의미를 지님. 즉 업무에 필요하고 유용한 정보를 저장하고 관리하기 위한 집합적인 것으로 설명할 수 있다.
  • EntityManager를 사용하면 어느 entity든 관리할 수 있다.(insert, update, delete, load, etc.) EntityManager는 단일 장소에서의 모든 entity repositories의 집합 같은 것이다.

.manager를 써도 실행이 되고, 안써도 mysqlDataSource.query()를 실행시킬 수 있다면 안쓰는 편이 좋다. 왜냐하면, 구조적으로 불필요한 절차를 생략시키고 가독성을 더 좋게 할 수 있기 때문이다. 그래서 이 글에서는 설명하기 위해 코드를 작성했지만, 다음 코드부터는 .manager()를 생략하여 사용할 것이다.

반응형