-
Notifications
You must be signed in to change notification settings - Fork 53
/
server.js
81 lines (68 loc) · 1.79 KB
/
server.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
// json-server
const path = require("path");
const jsonServer = require("json-server");
const server = jsonServer.create();
const router = jsonServer.router(path.join(__dirname, "db.json"));
const middlewares = jsonServer.defaults();
// lowdb
const low = require("lowdb");
const FileSync = require("lowdb/adapters/FileSync");
const adapter = new FileSync(path.join(__dirname, "db.json"));
const db = low(adapter);
server.use(middlewares);
server.use(jsonServer.bodyParser);
server.post("/products", (req, res) => {
const { price, name, imageUrl } = req.body;
if (
!Number.isInteger(price) ||
typeof name !== "string" ||
typeof imageUrl !== "string"
) {
res.sendStatus(400);
} else {
db.get("products").push({ id: Date.now(), price, name, imageUrl }).write();
res.sendStatus(201);
}
});
server.post("/carts", (req, res) => {
const { product } = req.body;
const { price, name, imageUrl } = product;
if (
!Number.isInteger(price) ||
typeof name !== "string" ||
typeof imageUrl !== "string"
) {
res.sendStatus(400);
} else {
db.get("carts").push({ id: Date.now(), product }).write();
res.sendStatus(201);
}
});
server.post("/orders", (req, res) => {
const { orderDetails } = req.body;
for (const orderDetail of orderDetails) {
const { quantity, price, name, imageUrl } = orderDetail;
if (
!Number.isInteger(quantity) ||
quantity < 1 ||
!Number.isInteger(price) ||
typeof name !== "string" ||
typeof imageUrl !== "string"
) {
res.sendStatus(400);
return;
}
}
db.get("orders")
.push({
id: Date.now(),
orderDetails,
})
.write();
res.sendStatus(201);
});
// default router
server.use(router);
server.listen(3003, () => {
console.log("JSON Server is running");
});