TIL 54일차 MVC 실습 마무리

shleecloud·2021년 10월 15일
0

Codestates

목록 보기
55/95

들어가며

이번 실습은 역대급으로 좋은 실습이었다. 실무와 가까우면서 적당히 어렵고 적당히 재밌다. 그러면서 테스트 케이스도 불합리하지도 복잡하지도 않고. 딱 좋았다. 딱 적절한 실습이고 약간의 아쉬움도 남으면서 주말의 과제까지 남겨주는 기가막힌 하루였다.
지금까지 배운 내용을 전부 버무렸다. NodeJS Express 문법 오랜만에 쓰니까 정말 햇갈리더라. 그래도 기억이 금방 돌아와서 코드를 쭉쭉 뽑아내는 재미가 있었다. MVC 모델에 대한 이해가 더 깊어진 느낌이다. 지금까지 배운 코드스테이츠 과정중 제일 재밌었다.

POST 구현

Controller Error exception

파라미터가 없는 경우의 에러처리가. 이 부분에서 테스트 케이스가 이루어졌다.

    post: (req, res) => {
      const userId = req.params.userId;
      const { orders, totalPrice } = req.body;
      // TODO: 자료가 누락될 경우 에러 처리
      if (!orders || !totalPrice || orders.length === 0) {
        return res.status(400).send('Internal Server Error in Controller');
      } else {
        // TODO: 요청에 따른 적절한 응답을 돌려주는 컨트롤러를 작성하세요.
        models.orders.post(userId, orders, totalPrice, (error, result) => {
          if (error) {
            res.status(400).send('Internal Server Error');
          } else {
            res.status(201).json(result);
          }
        });
      }
    },

Model Error exception

좋았던 부분은 Model 부분에서 에러처리다. 특히 db.beginTransaction() 이후 db.rollback() 또는 db.commit() 으로 DB의 정합성을 지킨 부분이 잘됐다. Controller 레벨에서 에러처리만 구현하면 DB에서 에러가 발생하는 경우 실행되지 않더라도 정상 동작으로 반환된다.

보완점

에러처리를 Try, Catch 문으로 하려고 했으나 callback 함수 안에서 throw error 문을 쓰더라도 다른 코드가 실행된다. else 문으로 담아주지 않으면 response 이후 코드도 실행되게 된다. 해결책을 생각해보면 몇가지 방법이 있다.

  • response 동작을 return으로 넘겨준다.
  • async, 비동기 처리로 넘겨준다.
post: (userId, orders, totalPrice, callback) => {
      // TODO: 해당 유저의 주문 요청을 데이터베이스에 생성하는 함수를 작성하세요
      // ! Trt Catch 왜 안돼..??
      // * DB Rollback Transaction 시작
      db.beginTransaction();

      // TODO orders Table Query
      const queryStringOrders = `INSERT INTO orders (user_id, total_price) VALUES (${userId}, ${totalPrice});`;
      db.query(queryStringOrders, (error, result) => {
        if (error) {
          db.rollback();
          //console.log(error);
          return callback(error, result);
        } else {
          // TODO order_items Join Table Query
          let orderId = result.insertId;
          const queryStringOrdersItems = `INSERT INTO order_items (order_id, item_id, order_quantity) VALUES ?;`;
          const params = orders.map(el => [orderId, el.itemId, el.quantity]);
          // * 다중 레코드 입력 [params]
          db.query(queryStringOrdersItems, [params], (error, result) => {
            if (error) {
              db.rollback();
              //console.log(error);
              return callback(error, result);
            } else {
              db.commit();
              return callback(error, result);
            }
          });
        }
      });
    },
profile
블로그 옮겼습니다. https://shlee.cloud

0개의 댓글