회원과 채널 백엔드 express : 고도화 중간점검

⭐ 아엔 Aen·2025년 9월 26일

데브코스

목록 보기
42/131

channels.js

const express = require("express");
const router = express.Router();

router.use(express.json());

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

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

  .post((req, res) => {
    if (req.body.channelTitle) {
      let channel = req.body;

      db.set(id++, channel);

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

  .get((req, res) => {
    var { userId } = req.body;
    var channels = [];

    if (db.size && userId) {
      db.forEach(function (value, key) {
        if ((value, userId === userId)) {
          channels.push(value);
        }
      });
    } else {
      notFoundChannel();
    }

    //예외처리 2가지
    // 1. userId가 body에 없으면
    // 2. userId가 가진 채널이 없으면, 이럴땐 200x, 404로!

    if (channels.length) {
      res.status(200).json(channels);
    } else {
      notFoundChannel();
    }
  }); //채널 전체 조회

router
  .route("/: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 {
      notFoundChannel();
    }
  }) //채널 개별 수정

  .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 {
      notFoundChannel();
    }
  }) //채널 개별 삭제

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

    if (channel) {
      res.status(200).json(channel);
    } else {
      notFoundChannel();
    }
  }); //채널 개별 조회

function notFoundChannel() {
  res.status(404).json({
    message: "채널 정보가 없습니다.",
  });
}

module.exports = router;

users.js

//express 모듈 세팅

const express = require("express");
const router = express.Router();

router.use(express.json()); //json형태로 된 body를 파싱하는 모듈
//http 외 모듈을 하나 사용할건데, 그게 json형태로 된 body를 파싱하는 모듈을 사용할거야.

let db = new Map();
var id = 1;
//로그인
router.post("/login", function (req, res) {
  //id가 디비에 저장된 회원인지 확인
  console.log(req.body);
  const { userId, password } = req.body;

  var loginUser = {}; //{}만 해도 객체가 됨

  db.forEach(function (user, id) {
    if (user.userId === userId) {
      loginUser = user;
    }
  });

  if (isExist(loginUser)) {
    console.log("로그인 성공");
    if (loginUser.password === password) {
      console.log("비밀번호 일치");
    } else {
      console.log("비밀번호 불일치");
    }
  } else {
    console.log("존재하지 않는 계정입니다.");
  }
});

function isExist(loginUser) {
  if (Object.keys(loginUser).length) {
    return true;
  } else {
    return false;
  }
}

// 회원가입

router.post("/join", function (req, res) {
  console.log(req.body);

  if (req.body == {}) {
    res.status(400).json({
      message: `회원가입에 실패하였습니다. 다시 시도해주세요.`,
    });
  } else {
    db.set(id++, req.body);
    res.status(201).json({
      message: `${db.get(id - 1).name}님 회원가입을 축하드립니다.`,
    });
  }
});

// 회원 개별 조회
router
  .route("users/:id")
  .get(function (req, res) {
    let { id } = req.params;
    /*{id} 이게 뭐냐면! 너 id값 있던데, 그 id값 바로 꺼내서 id라는변수에 바로 담아줘. 라는 뜻이야*/
    id = parseInt(id);
    const user = db.get(id);
    if (user == undefined) {
      res.status(404).json({
        message: "회원 정보가 없습니다.",
      });
    } else {
      res.status(200).json({
        userId: user.userId,
        name: user.name,
      });
    }
  })

  //회원 개별 탈퇴

  .delete(function (req, res) {
    let { id } = req.params;
    /*{id} 이게 뭐냐면! 너 id값 있던데, 그 id값 바로 꺼내서 id라는변수에 바로 담아줘. 라는 뜻이야*/
    id = parseInt(id);

    const user = db.get(id);
    if (user == undefined) {
      res.status(404).json({
        message: "회원 정보가 없습니다.",
      });
    } else {
      db.delete(id);

      res.status(200).json({
        message: `${user.name}님 다음에 또 뵙겠습니다!`,
      });
    }
  });

module.exports = router;

app.js

const express = require("express");
const app = express();

app.listen(7777);

const userRouter = require("./routes/users"); // user-demo 어떻게 소환? 이렇게 소환
const channelRouter = require("./routes/channels"); // channel-demo 어떻게 소환? 이렇게 소환

app.use("/", userRouter);
app.use("/channels", channelRouter); //이런식으로 공통적으로 사용되는 url은 빼줘서 좀 더 간단하게 가능해!
//내가 만들어논 유저 데모에 모듈이 소환이 되어서 그걸 마치 미들웨어처럼 app.use를 사용해서 여러분들의 userRouter를 추가를 해준거야.
profile
Dive Head First | Work Super Hard | Attract Great People

0개의 댓글