[Supinfo][Node.js] Products CRUD API 만들기

박현아·2025년 10월 5일
0

SUPINFO

목록 보기
1/5

자바스크립트 오랜만에 하니까 어렵다
학교에서 한 실습 중 유용한 한 개 기록

👩‍💻 문제

🙋‍♀️ 답변

let products = [
    {id: 1, name: "Laptop", price: 1200},
    {id: 2, name: "Headphones", price: 150},
    {id: 3, name: "Keyboard", price: 70},
    {id: 4, name: "Mouse", price: 40},
    {id: 5, name: "Monitor", price: 300}
];

// Import the express library
const express = require("express");

// Initializing the app
const app = express();

app.use(express.json());
// app.use() : 요청 바디(request body)를 JSON으로 파싱하는 내장 미들웨어
// express.json()
// : 요청 바디(request body)를 JSON으로 파싱하는 내장 미들웨어
// 클라이언트가 보낸 JSON 데이터를 request.body로 바로 사용할 수 있게 만들어줌

// CREATE
app.post("/products", (request, response)=> {
    const newProduct = request.body; // OBJECT JS
    console.log(newProduct); 
    products.push(newProduct);
    response.status(201).send(products);
    // response.json(products);
});

// READ ALL (+ 필터 기능)
// 쿼리 파라미터 - request.query
app.get("/products", (request, response)=> {

    const query = request.query; // 쿼리 파라미터 전체 가져오기
    console.log(query);

    // let name = query.name;
    // let minPrice = query.minPrice;
    // let maxPrice = query.maxPrice;

    // 객체 구조 분해 할당 (Object destructuring assignment)
    let { name, minPrice, maxPrice } = query;

    // 문자열 -> 숫자 변환
    minPrice = minPrice ? Number(minPrice) : undefined;
    maxPrice = maxPrice ? Number(maxPrice) : undefined;

    // 새로운 배열로 필터링
    let filtered = products;

    // 이름 검색 (부분 일치도)
    if(name) {
        filtered = filtered.filter(p => {
            return p.name.toLowerCase().includes(name.toLowerCase());
        });
    }

    // 최소 가격
    if(minPrice !== undefined) {
        filtered = filtered.filter(p => {
            return p.price >= minPrice
        });
    }

    // 최대 가격
    if(maxPrice) {
        filtered = filtered.filter(p => {
            return p.price <= maxPrice
        });
    }

    response.status(200).json(filtered);
});

// READ ONE
// (경로) 파라미터 - request.params
app.get("/products/:id", (request, response)=> {
    const id = parseInt(request.params.id); // 모든 params 중에 id를 가져온다 (String 형식)
    console.log("Product id : " + id);
    const product = products.find(p=> p.id===id);
    console.log(product);

    if (!product) {
        return response.status(404).send({ message: "Product not found" });
    }

    response.status(200).send(product);
})

// UPDATE
app.put("/products/:id", (request, response)=> {
    const id = parseInt(request.params.id); // 모든 params 중에 id를 가져온다 (String 형식)
    console.log("Product id : " + id);
    const product = products.find(p=> p.id===id);
    console.log(product);

    if (!product) {
        return response.status(404).send({ message: "Product not found" });
    }

    const { name, price } = request.body;

    if(name) product.name = name;
    if(price !== undefined) product.price = price;

    response.status(200).send(product);
});

// DELETE
app.delete("/products/:id", (request, response)=> {
    const id = parseInt(request.params.id); // 모든 params 중에 id를 가져온다 (String 형식)
    console.log("Product id : " + id);
    const product = products.find(p=> p.id===id);

    if (!product) {
        return response.status(404).send({ message: "Product not found" });
    }
    
    products = products.filter(p=> p.id !== id);

    response.status(200).send(products);
});



app.listen(8080, (err)=> {
    console.log("Server running on http://localhost:8080");
});

🤔

  • request.params.id 나 request.body.minPrice 결과가 String이니까 int로 변경해주기
  • int로 변경해줬을 때 NaN 뜨지 않게 undefined 처리해주기
  • 객체 구조 분해 할당 사용해서 간결하게 하기
  • 없는 제품 검색했을 때 404 리턴해주는 게 좋은가? (더 RESTful 하다고 한다) : 어떤 경우에 404 리턴해주고 어떤 경우에 null 리턴해주는 게 좋은지?
  • response.send()와 response.json() 사용의 차이

0개의 댓글