스파르타 코딩 클럽 node.js 3주차 숙제

Justin. S. Hong·2022년 8월 21일
0

스파르타코딩클럽

목록 보기
6/11

1번 숙제
장바구니의 상품 수량을 수정하는 API에서 수량을 1보다 작게 입력할 경우 요청을 거부하기

router.put("/goods/:goodsId/cart", async (req, res) => {
  const { goodsId } = req.params;
  const { quantity } = req.body;

  if (quantity < 1) {
    res.status(400).json({ errorMessage: "수량을 잘못 입력하셨습니다. 수량은 1 이상으로 입력해주세요." });
    return;
  }

  const existsCarts = await Cart.find({ goodsId: Number(goodsId) });
  if (existsCarts.length) {
    await Cart.updateOne({ goodsId: Number(goodsId) }, { $set: { quantity } });
  }

  res.json({ success: true });
});

2번 숙제
장바구니의 목록을 조회하는 API에서 경로 변경

/***** /routes/goods.js *****/
// routes/cart.js의 코드를 routes/goods.js로 이동

router.get("/goods/cart", async (req, res) => {
    const carts = await Carts.find();
    const goodsIds = carts.map((cart) => cart.goodsId);

    const goods = await Goods.find({ goodsId: goodsIds });

    res.json({
        carts: carts.map((cart) => ({
                quantity: cart.quantity,
                goods: goods.find((item) => item.goodsId === cart.goodsId),
        })),
    })
});

/***** /app.js  *****/
const goodsRouter = require("./routes/goods");
// const cartsRouter = require("./routes/cart");   <- cart가 필요없어졌으니 제거

const requestMiddleware = (req, res, next) => {
    console.log("Request URL:", req.originalUrl, " - ", new Date());
    next();
};
profile
KOSA -> 오즈코딩스쿨을 거쳐 프론트엔드 개발자로 성장하기 ESTJ-1W2

0개의 댓글