[데이터베이스] MVC Cmarket Database - Controller

윤후·2022년 3월 13일
0

Section 3

목록 보기
26/41

Sprint풀이


controller/index.js

const models = require('../models');

module.exports = {
  items: {
    get: (req, res) => {
      models.items.get((error, result) => {
        if (error) {
          res.status(500).send('Internal Server Error');
        } else {
          res.status(200).json(result);
        }
      });
    },
  },
  orders: {
    get: (req, res) => {
      const userId = req.params.userId;
      // TODO: 요청에 따른 적절한 응답을 돌려주는 컨트롤러를 작성하세요.
      
      if(!userId){
        res.status(400).json({'please': 'check userId'})
      }

      models.orders.get(userId, (err, result) => {
        if(err){
          res.status(500).send('Internal Server Error');
        } else {
          res.status(200).json(result)
        }
      })
      

    },
    post: (req, res) => {
      const userId = req.params.userId;
      const { orders, totalPrice } = req.body;

      if(!orders || !totalPrice || !userId){
        return res.status(400).json({'please':'check userId'})
      }
      models.orders.post(userId, orders, totalPrice,(err, result) => {
        if(err){
          res.status(500).send('Internal Server Error')
        } else{
          res.status(201).send({orders : orders, totalPrice : totalPrice})
        }
      })
      // TODO: 요청에 따른 적절한 응답을 돌려주는 컨트롤러를 작성하세요.
    },
  },
};

이제 route에서 궁금했던 부분을 시원하게 긁어줄 controller/index.js파일을 보자. MVC에서 controller의 역할은 View과 Model을 이어주는 역할을 한다. View에서 일어나는 Event는 route를 통해 분기되고 Event와 관련된 데이터를 Model에게 전달해주고, 다시 Model에게 받은 데이터를 View가 소화할 수 있게 가공하고 전달하게 된다.

주의점.

post: (req, res) => {
      const userId = req.params.userId;
      const { orders, totalPrice } = req.body;

      if(!orders || !totalPrice || !userId){
        res.status(400).json({'please':'check userId'})
      }

Cmarket Database
"before each" hook for "POST /users/:userId/orders 요청에 성공했을 경우 상태코드 201을 보내야합니다.":
Uncaught TypeError: Cannot read property 'map' of undefined

사실 위와 같이 if( !orders || !totalPrice || !userId )의 조건문에 return문을 붙여주지 않았었다. 헌데, 계속 위와 같은 경고문이 뜨는게 문제였다. 이러한 문제가 뜨는 이유는 models/index.js에서 map을 사용하고 있는 orders에 관한 문제였다.

if(!orders || !totalPrice || !userId){
        res.status(400).json({'please':'check userId'})
      }

orders가 undefined이라면, 위의 조건문에 해당하여 아래의 코드를 실행하지만

res.status(400).json({'please':'check userId'})

콜백함수는 종료되지 않고 그 다음 코드를 실행하게 된다.

models.orders.post(userId, orders, totalPrice,(err, result) => {
        if(err){
          res.status(500).send('Internal Server Error')
        } else{
          res.status(201).send({orders : orders, totalPrice : totalPrice})
        }
      })

return 되지 않아 콜백함수가 끝나지 않기 때문에 orders가 undefined인 상태로 models/index.js로 넘어가게 되는 것이였다.

하여 위와 같은 상황이 생기지 않도록 하기 위해서 return문을 꼭 써주어 이러한 오류를 미연에 방지해야겠다

if(!orders || !totalPrice || !userId){
        return res.status(400).json({'please':'check userId'})
      }
profile
궁금한걸 찾아보고 공부해 정리해두는 블로그입니다.

0개의 댓글

관련 채용 정보