유튜브의 영상의 task를 영어로 번역하였음. 각 task에 맞는 적절한 코드를 써보도록 하자. 아래의 기본적인 코드는 생략하겠음
import express from 'express';
const app=express();
const port=process.env.port||3000;
app.listen(port,()=>{
console.log(`Running on ${port}`);
})
const products=[
{
id:1,
label:"cookie",
popular:5
},
{
id:2,
label:"pizza-2",
popular:3
},
{
id:3,
label:"pizza-3",
popular:2
}
]
1. "Here is a task for you to complete. First, write a line of code to display 'Welcome to our project main page' using the GET method. Remember, the URL for this content should be '/'."
app.get('/',(req,res)=>{
res.send("Welcome to our home page");
})
2. "We prepare a list containing maps with keys as id and values as product-name. At the URL '/products', you can view the entire array of product information on your screen. Write a line of code to display them."
app.get("/products",(req,res)=>{
res.send(products);
})
3. "We have created a router at 'api/products/' with a router parameter id. Your task is to write a line of code to filter out the record where the id matches the parameter."
//get a product whose id matches paramater id
app.get("/api/product/:id",(request,response)=>{
//parse integer of id
const parseId=parseInt(request.params.id);
if(isNaN(parseId))
return response.status(400).send({msg:"Bad Request.Invalind ID."});
const findProduct=products.find((product)=>product.id===parseId);
if(!findProduct) return response.sendStatus(404);
return response.send(findProduct);
});
4. "In this task, you are required to write a line of code to filter data where the id contains the string from the query parameter."
app.get("/api/products",(request,response)=>{
const{query:{filter,value},}=request;
if(!filter && !value) return response.send(products);
if(filter&&value)
return response.send(
products.filter((product)=>product[filter].includes(value))
);
});
5. Users can add a new record to the existing 'product' array using the request method. The unique 'id' for the newly added record will be one greater than the last index of the array.
import express from 'express';
const app=express();
//add the following code of line
app.use(express.json());
const port=process.env.port||3000;
answer)
app.post("/api/products",(req,res)=>{
const {body}=req;
const newData={id:products[products.length-1].id+1,...body};
products.push(newData);
res.sendStatus(201);
})
5. Now, we want to replace the existing record with the newly entered one. For this task, you need to prepare the sections for parameters and body that users will send to the router.
//PUT//////////////////////////////////////////////
app.put("/api/products/:id",(req,res)=>{
const{
body,
params:{id},
}=req;
const parsedId=parseInt(id);
if(isNaN(parsedId))
res.status(404).send({msg:"Bad request!"});
const productIndex=products.findIndex((product)=>product.id===parsedId);
products[productIndex]={id:parsedId,...body};
res.send(products).status(200);
})
6. Given the parameter (i.e., id), you need to write a line of code to delete the corresponding record from the data array.
//Delete/////////////////////////////
app.delete("/api/products/:id",(req,res)=>{
const{
params:{id},
}=req;
const parsedId=parseInt(id);
if(isNaN(parsedId)) return res.sendStatus(400);
const findIndex=products.findIndex((product)=>product.id===parsedId);
if(findIndex===-1) return res.sendStatus(404);
products.splice(findIndex);
return res.status(200).send({msg:`The record with id=${id} has been successfully deleted! `});
})
7. Here is a brief explantion of how middleware works.
In JavaScript, particularly in the context of web development, middleware refers to functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. Middleware functions are used to modify the request and response objects or to perform specific actions before passing control to the next function in the stack.
Key Characteristics of Middleware:
Order Matters: Middleware is executed in the order it is defined.
Chaining: Middleware functions call next() to pass control to the next middleware in the stack. If next() is not called, the request-response cycle will be halted.
Use Cases:
Logging requests
Parsing request bodies (e.g., JSON, form data)
Handling authentication
Serving static files
Error handling
Q1) Now, you are required to write a logging middleware that applies globally. The logging middleware should log the time, request URL, and HTTP method.
const logginMiddleware=(req,res,next)=>{
const currentDateTime=new Date();
console.log(`[${currentDateTime}] ${req.method} ${req.url}`);
next();
}
app.use(logginMiddleware);
Q2) "Instead of applying the logging middleware globally, you need to assign it to a specific app router in JavaScript."
//erase this
//app.use(logginMiddleware);
app.get("/products",logginMiddleware,(req,res)=>{
res.json(products);
})
8. Please review the following lines of code, and you'll notice some duplicate sections that could be replaced with a function to eliminate redundancy. Here's what you should do: write a middlware called findIndex to locate the index of a record that matches a given condition.
//PUT//////////////////////////////////////////////
app.put("/api/products/:id",(req,res)=>{
const{
body,
params:{id},
}=req;
const parsedId=parseInt(id);
if(isNaN(parsedId))
res.status(404).send({msg:"Bad request!"});
const productIndex=products.findIndex((product)=>product.id===parsedId);
products[productIndex]={id:parsedId,...body};
res.send(products).status(200);
})
//Delete/////////////////////////////
app.delete("/api/products/:id",(req,res)=>{
const{
params:{id},
}=req;
const parsedId=parseInt(id);
if(isNaN(parsedId)) return res.sendStatus(400);
const productIndex=products.findIndex((product)=>product.id===parsedId);
if(productIndex===-1) return res.sendStatus(404);
products.slice(productIndex);
return res.status(200).send({msg:`The record with id=${id} has been successfully deleted! `});
})
Answer)
//PUT//////////////////////////////////////////////
app.put("/api/products/:id",resolveByUserIndex,(req,res)=>{
const{
body,
params:{id},
}=req;
const parsedId=parseInt(id);
products[req.findIndex]={id:parsedId,...body};
res.send(products).status(200);
})
//Delete/////////////////////////////
app.delete("/api/products/:id",resolveByUserIndex,(req,res)=>{
products.splice(req.findIndex,1);
return res.status(200).send({msg:`The record with id=${req.params.id} has been successfully deleted! `});
})