채널 API 설계 완료!

데브코스

목록 보기
40/131
const express = require("express");
const app = express();
app.listen(7777);
app.use(express.json());

let db = new Map();
var id = 1;

//채널 개별 생성
app
  .route("/channels")

  .post((req, res) => {
    if (req.body.channelTitle) {
      db.set(id++, req.body);
      res.status(201).json({
        message: `${db.get(id - 1).channelTitle} 채널을 응원합니다.`,
      });
    } else {
      res.status(400).json({
        message: `채널 생성에 실패하였습니다. 다시 시도해주세요.`,
      });
    }
  })

  .get((req, res) => {
    if (db.size) {
      var channels = [];

      db.forEach(function (value, key) {
        channels.push(value);
      });
      res.status(201).json(channels);
    } else {
      res.status(404).json({
        message: `조회할 채널이 없습니다.`,
      });
    }
  }); //채널 전체 조회

app
  .route("/channels/:id")

  .put((req, res) => {
    let { id } = req.params;
    id = parseInt(id);
    var channel = db.get(id);
    var oldTitle = channel.channelTitle;

    if (channel) {
      var newTitle = req.body.channelTitle;
      channel.channelTitle = newTitle;
      db.set(id, channel);

      res.status(200).json({
        message: `${oldTitle} 채널이 ${newTitle} 채널로 수정되었습니다.`,
      });
    } else {
      res.status(404).json({
        message: `채널 정보가 없습니다.`,
      });
    }
  }) //채널 개별 수정

  .delete((req, res) => {
    let { id } = req.params;
    id = parseInt(id);
    var channel = db.get(id);

    if (channel) {
      db.delete(id);
      res.status(200).json({
        message: `${channel.channelTitle} 채널이 삭제되었습니다.`,
      });
    } else {
      res.status(404).json({
        message: `채널 정보가 없습니다.`,
      });
    }
  }) //채널 개별 삭제

  .get((req, res) => {
    let { id } = req.params;
    id = parseInt(id);
    var channel = db.get(id);

    if (channel) {
      res.status(200).json(channel);
    } else {
      res.status(404).json({
        message: "채널 정보가 없습니다.",
      });
    }
  }); //채널 개별 조회

profile
Dive Head First | Work Super Hard | Attract Great People

0개의 댓글