Express.Router를 이용한 collection 관리

sangyong park·2023년 3월 6일

Express.Router를 이용하여 collection 관리

collection이 많아질수록 서버의 index.js 파일의 코드 양이 많아져서 유지보수에 불합리 하다.

이럴때 폴더를 분리하여 연결 해주는 Express.Router를 사용해보자

server > Router > post.js

Router 폴더를 하나 생성한 뒤 자신이 작업하는 collection에 관련된 파일을 하나 만들어준다.

post.js 라는 파일에 post에 관련된 서버쪽 데이터를 다 가져와 넣어준다.

여기서 이제 기존에 app.post() 와 같이 되어있는 것들을 router.post()로 변경해준다.

또한 해당 Router에서 사용하는 Model 선언문도 가져와 넣어준다.

<script>
var express = require("express");
var router = express.Router();

const { Post } = require("../Model/Post");
const { Counter } = require("../Model/Counter");

// client에서 보낸 api 요청을 받는 코드
router.post("/submit", (req, res) => {
  // client에서 보낸 body 값을 temp 변수에 지정
  let temp = req.body;
  // Counter 콜렉션에서 name: "counter"인 애들을 찾아서 temp 변수를 통해서 posts 모델의 postNum에 집어넣어준다.
  Counter.findOne({ name: "counter" })
    .exec()
    .then((counter) => {
      temp.postNum = counter.postNum;
      // new 명령어를 통해서 Model안에 들어갈 데이터를 정의해준다.
      // save 명령어를 통해서 저장
      const CommunityPost = new Post(temp);
      CommunityPost.save().then(() => {
        // 몽고 디비에서 하나의 다큐먼트를 업데이트 하는 명령어 , 두개의 query를 받는다 첫번째 쿼리는 어떤 다큐먼트를 업데이트 시킬지, 두번째는 어떻게 업데이트 시킬지
        // query문에서 증가시키는 코드는 $inc를 통해 가능하다.
        Counter.updateOne({ name: "counter" }, { $inc: { postNum: 1 } }).then(
          () => {
            res.status(200).json({ success: true });
          }
        );
      });
    })
    .catch(() => {
      res.status(400).json({ success: false });
    });
});

// submit에 들어간 데이터를 받는 서버쪽 코드
router.post("/list", (req, res) => {
  // find() 몽고디비에서 document를 찾는 명령어
  Post.find()
    .exec()
    .then((doc) => {
      res.status(200).json({ success: true, postList: doc });
    })
    .catch(() => {
      res.status(400).json({ success: false });
    });
});

router.post("/detail", (req, res) => {
  Post.findOne({ postNum: Number(req.body.postNum) })
    .exec()
    .then((doc) => {
      console.log(doc);
      res.status(200).json({ success: true, post: doc });
    })
    .catch(() => {
      res.status(400).json({ success: false });
    });
});

router.post("/edit", (req, res) => {
  let temp = {
    title: req.body.title,
    content: req.body.content,
  };
  Post.updateOne({ postNum: Number(req.body.postNum) }, { $set: temp })
    .exec()
    .then(() => {
      res.status(200).json({ success: true });
    })
    .catch(() => {
      res.status(400).json({ success: false });
    });
});

router.post("/delete", (req, res) => {
  Post.deleteOne({ postNum: Number(req.body.postNum) })
    .exec()
    .then(() => {
      res.status(200).json({ success: true });
    })
    .catch(() => {
      res.status(400).json({ success: false });
    });
});

module.exports = router;
</script>

이제 위와같이 파일을 만든 것을 서버의 index.js 에 넣어주는 작업

app.use() 를 사용하여 router 파일을 선언해준다. 여기서 라우팅 규칙이 공통적으로 적용이 되는 것은 app.use("/api/post") 와 같이 작성 해주고 라우터 파일에서 router.post(/api/post/delete) 부분을 router.post(/delete) 와 같이 사용할 수 있다.

<script>
app.use("/api/post", require("./Router/post"));
</script>
profile
Dreams don't run away It is always myself who runs away.

0개의 댓글