-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjunk.js
101 lines (79 loc) · 2.16 KB
/
junk.js
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
const express = require("express");
const app = express();
const fs = require("fs");
//this is how we use middleware
app.use(express.json());
// app.get('/', (req,res)=>{
// res.status(200)
// .json({message: 'hello from the server side !!',app: 'natours'});
// });
// app.post('/', (req,res)=>{
// res.end("this is post endpoint");
// });
//top-level code,sync,blocking code
const tours = JSON.parse(
fs.readFileSync(`${__dirname}/dev-data/data/tours-simple.json`)
);
//route handler
//get method
app.get('/api/v1/tours/:id?',(req,res)=>{
// finding particular thing in id by requesting parameters
console.log(req.params);
//convert parameter string into number
const id = req.params.id*1;
//find id by find array method in tours
const tour = tours.find(el =>el.id=== id);
//if id is not in database
//if(!tour)
if( id > tours.length){
return res.status(404).json({
status:'fail',
message:'Invalid ID'
});
};
//if id is found in databse
res.status(200).json({
status:'success',
data:{
tour
}
});
});
//post method
app.post('/api/v1/tours',(req,res)=>{
// console.log(req.body);
//assigning id and if added then adding them into array
const newId = tours[tours.length-1].id+1;
const newTour = Object.assign({id:newId},req.body);
//if new tours are added then write them in our tours file
tours.push(newTour);
fs.writeFile(`${__dirname}/dev-data/data/tours-simple.json`, JSON.stringify(tours), err=>{
res.status(201).json({
status: "success",
data:{
tour :newTour
}
}).send();
})
// res.send('done');
});
//patch method (updates only the properties that user updated)
app.patch('/api/v1/tours/:id',(req,res)=>{
if( req.params.id*1 > tours.length){
return res.status(404).json({
status:'fail',
message:'Invalid ID'
});
}
res.status(200).json({
status:"success",
data:{
tour:'<updated tour>'
}
})
})
//app server
const port = 3000;
app.listen(port , ()=>{
console.log("app running on port 3000");
});