Node.js | API 구현하기

bubblegum·2024년 1월 19일

NodeJS

목록 보기
3/14
post-thumbnail
/routes/goods.js

import express from 'express';

//익스프레스에 라우터 생성
const router = express.Router();

//1. mongoose, Goods 모델 가져오기 
import mongoose from 'mongoose';
import Goods from '../schemas/goods.js';

//2. API 구현
router.post('/goods', async(req, res)=>{
  // 3. 클라이언트로부터 전달받은 데이터를 가져온다
  // goodsId, name, thumbnailUrl, category, price
  const {goodsId, name, thumbnailUrl, category, price} = req.body; 
  
  // 4. goodsId 중복되면 에러메시지를 전달한다. -> 실제로 MongoDB에 데이터를 조회해서, 해당하는 데이터가 MongoDB에 존재하는지 확인한다. 
  const goods = await Goods.find({goodsId: goodsId}).exec(); // promise문으로 동작하게 하기 위한 장치. 데이터를 조회할 때 사용한다. 
  
  // 4-1. 만약, goodsId가 중복되다면, 에러메시지를 전달한다. 
  if(goods.length){
    return res.status(400).json({errorMessage: '이미 존재하는 데이터입니다.'});
  }
  // 5. 상품(Goods)를 생성한다.
  const createdGoods = await Goods.create({
    goodsId: goodsId, 
    name: name, 
    thumbnailUrl: thumbnailUrl, 
    category: category, 
    price: price,
  });

  // 6. 생성된 상품 정보를 클라이언트에게 응답(response) 반환한다. 
  return res.status(201).json({goods: createdGoods}); 
}); 

export default router;  
profile
황세민

0개의 댓글