-
Notifications
You must be signed in to change notification settings - Fork 0
/
app-before-partition.js
112 lines (96 loc) · 2.21 KB
/
app-before-partition.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
102
103
104
105
106
107
108
109
110
111
112
const fs = require('fs');
const express = require('express');
const app = express();
// MIDDLEWARES
app.use(express.json());
const tours = JSON.parse(
fs.readFileSync(`${__dirname}/dev-data/data/tours-simple.json`)
);
const getAllTours = (req, res) => {
res.status(200).json({
status: 'success',
results: tours.length,
data: {
tours
}
});
};
const getTour = (req, res) => {
console.log(req.params);
const id = req.params.id * 1; // to convert string to number
const tour = tours.find(el => el.id === id);
// if (id > tours.length) {
if (!tour) {
return res.status(404).json({
status: 'fail',
message: 'Invalid ID'
});
}
res.status(200).json({
status: 'success',
data: {
tour
}
});
};
const createTour = (req, res) => {
//console.log(req.body);
const newId = tours[tours.length - 1].id + 1;
const newTour = Object.assign({ id: newId }, req.body);
tours.push(newTour);
fs.writeFile(
`${__dirname}/dev-data/data/tours-simple.json`,
JSON.stringify(tours),
err => {
res.status(201).json({
status: 'succcess',
data: {
tour: newTour
}
});
}
);
};
const updateTour = (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 here...>' } });
};
const deleteTour = (req, res) => {
if (req.params.id * 1 > tours.length) {
{
return res.status(404).json({
status: 'fail',
message: 'Invalid ID'
});
}
}
res.status(204).json({ status: 'success', data: null });
};
// app.get('/api/v1/tours', getAllTours);
// app.post('/api/v1/tours', createTour);
// app.get('/api/v1/tours/:id', getTour);
// app.patch('/api/v1/tours/:id', updateTour);
// app.delete('/api/v1/tours/:id', deleteTour);
app
.route('/api/v1/tours')
.get(getAllTours)
.post(createTour);
app
.route('/api/v1/tours/:id')
.get(getTour)
.patch(updateTour)
.delete(deleteTour);
// Start server
const port = 3000;
app.listen(port, () => {
console.log(`App running on port ${port}...`);
});