-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path23-querry-string.js
More file actions
53 lines (49 loc) · 1.48 KB
/
Copy path23-querry-string.js
File metadata and controls
53 lines (49 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
const express = require('express')
const app = express()
const {products} = require('./node-express-course/02-express-tutorial/data.js')
app.get('/',(req,res)=>{
res.send('<h1>Home page</h1><a href="/api/products">products</a>')
})
app.get('/api/products',(req,res)=>{
const newProducts = products.map((product)=>{
const {id,name,image} = product;
return {id,name,image}
})
res.json(newProducts)
})
app.get('/api/products/:productID',(req,res)=>{
// console.log(req);
// console.log(req.params);
const {productID} = req.params
const singleProduct = products.find((product)=> product.id === Number(productID))
if(!singleProduct){
res.status(404).send(' <h1>no such id exists</h1> ')
}
res.json(singleProduct)
})
app.get('/api/v1/query',(req,res)=>{
// console.log(req.query);
const {search,limit} = req.query
let sortedProducts = [...products];
if(search){
sortedProducts = sortedProducts.filter((product)=>{
return product.name.startsWith(search)
})
}
if(limit){
sortedProducts = sortedProducts.slice(0,Number(limit))
}
if (sortedProducts.length<1) {
// res.send("sorry !! product not found")
// console.log("product not found");
res.status(200)
res.json({
sucess: true,
data: []
})
}
res.status(200).json(sortedProducts)
})
app.listen(5005,()=>{
console.log('server is listening to port : 5005');
})