본문 바로가기
  • 삽질하는 자의 블로그
Node.js(Express)

5. MVC 패턴, Contoroller 의 사용 // 여러개의 미들웨어

by 이게뭐당가 2023. 2. 18.

Routes 폴더에는, 우리가 만들어주는 연결고리인 route 만 있는 것이 좋다.

이게 무슨 뜻이나면, 로직은 컨트롤러에 따로 빼서, 사용하는 것이 적절하다는 말이다.

이는 MVC 패턴의 Contoller 에 해당하고, 이는 로직을 담당하는 역할을 한다.

 

contoller 폴더에 로직을 따로정리해보자.

 

1. 기존의 Routes 폴더 안의 Route

 < router / diary.js >

                ...
        router.get("/:userEmail", (req, res, next) => {
            const userEmail = req.params.userEmail;

            if (!userEmail.includes("@")) {
                const error = new Error("이메일이 올바르지 않습니다.") 
                error.code = 404
                next(error) 
                return 
            }   
            res.json({ message: "this is diary" });
        });

        module.exports = router;

 

2. 컨트롤러에 로직을 리팩토링 한 Route 와 Contoller

 

< controllers / diary-controller.js >		// contollers 폴더 안에 로직을 아웃소싱한다.

    const getUserDiary = (req, res, next) => {
        const userEmail = req.params.userEmail;

        if (!userEmail.includes("@")) {
            const error = new Error("이메일이 올바르지 않습니다.");
            error.code = 404;
            next(error);
            return;
        }
        res.json({ message: "this is diary" });
    };

    exports.getUserDiary = getUserDiary     // export 한다.

-----------------------------

< routes / diary-routes.js >	

    const express = require("express");
    const diaryContoller = require("../controllers/diary-controller");  // 가져와서

    const router = express.Router();

    router.get("/:userEmail", diaryContoller.getUserDiary);     // 해당 미들웨어에 넣는다.

    module.exports = router;

 

 

3. 여러개의 미들웨어

    < routes / diary-routes.js >

        const express = require("express")

        const router = express.Router()

        router.get("/:userEmail", diaryContoller.getUserDiary);

    ------------

    기본적으로 하나의 미들웨어만 되어있지만
    필요에 의해

        router.get("/:userEmail", 미들웨어1, 미들웨어2, ..., diaryContoller.getUserDiary);

    이렇게 여러개의 미들웨어를 추가적으로 사요할 수 도 있다.

    이때 미들웨어는 왼쪽부터 차례대로 실행된다.

    이곳에 "추가적인 Validation 미들웨어" 를 넣을 수도 있다.

댓글