-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
88 lines (77 loc) · 1.82 KB
/
app.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
const fs = require('fs');
const express = require('express');
const app = express();
app.use(express.json());
const PORT = 5555;
const products = JSON.parse(fs.readFileSync(`${__dirname}/data/products.json`));
const getAllProducts = (req, res) => {
res.status(200).json({
status: 'success',
result: products.length,
data: {
products,
},
});
};
const getProduct = (req, res) => {
const id = req.params.id * 1;
const product = products.find(el => el.id * 1 === id);
if (!product || !product.id) {
res.status(404).json({
status: 'error',
message: 'Product not found',
});
}
res.status(200).json({
status: 'success',
result: products.length,
data: {
product,
},
});
};
const addProduct = (req, res) => {
const newId = parseInt(products[products.length - 1].id) + 1;
const newProduct = Object.assign({id: newId}, req.body);
products.push(newProduct);
fs.writeFile(
`${__dirname}/data/products.json`,
JSON.stringify(products),
error => {
res.status(201).json({
status: 'success',
data: {
product: newProduct,
},
});
},
);
};
const updateProduct = (req, res) => {
res.status(200).json({
status: 'success',
data: {
product: 'updated',
},
});
};
const deleteProduct = (req, res) => {
res.status(204).json({
status: 'success',
data: null,
});
};
app.get('/', (req, res) => {
res.status(200).json({
status: 'success',
data: 'Api v1.0.2 . Automate pull image'
})
});
app.get('/api/v1/products', getAllProducts);
app.get('/api/v1/products/:id', getProduct);
app.post('/api/v1/products', addProduct)
app.patch('/api/v1/products/:id', updateProduct);
app.delete('/api/v1/products/:id', deleteProduct);
app.listen(PORT, () => {
console.log('Server start at port: ' + PORT);
});