-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
71 lines (61 loc) · 1.87 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
const express = require("express");
const { randomUUID } = require("crypto");
const fs = require("fs");
const app = express();
app.use(express.json()) //middleman
let products = [];
fs.readFile("products.json", "utf-8", (err, data) => {
if (err) {
console.log(err);
} else {
products = JSON.parse(data);
}
});
app.get("/products", (request, response) => {
return response.json(products);
});
app.get("/products/:id", (request, response) => {
const { id } = request.params;
const product = products.find((product) => product.id === id);
return response.json(product);
});
app.post("/products", (request, response) => {
const { name, price } = request.body;
const product = {
id: randomUUID(),
name,
price
}
products.push(product);
refreshProductFile();
return response.json(product);
});
app.put("/products/:id", (request, response) => {
const { id } = request.params;
const { name, price } = request.body;
const productIndex = products.findIndex(product => product.id === id);
products[productIndex] = {
...products[productIndex],
name,
price
};
refreshProductFile();
return response.json({ message: "Produto alterado com sucesso" });
});
app.delete("/products/:id", (request, response) => {
const { id } = request.params;
const productIndex = products.findIndex(product => product.id === id);
products.splice(productIndex, 1);
refreshProductFile();
return response.json({ message: "Produto deletado com sucesso" });
});
function refreshProductFile() {
fs.writeFile("products.json", JSON.stringify(products), (err) => {
if (err) {
console.log(err);
} else {
console.log("Produto cadastrado com sucesso");
}
});
}
app.listen(4002, () => console.log("Servidor rodando na porta 4002"));