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

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");
});