-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
94 lines (64 loc) · 2.34 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
89
90
91
92
93
94
import fs from "node:fs/promises";
import bodyParser from "body-parser";
import express from "express";
const app = express();
app.use(express.static("images"));
app.use(bodyParser.json());
// CORS
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*"); // allow all domains
res.setHeader("Access-Control-Allow-Methods", "GET, PUT, DELETE");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
next();
});
app.get("/places", async (req, res) => {
await new Promise((resolve) => setTimeout(resolve, 3000));
const fileContent = await fs.readFile("./data/places.json");
const placesData = JSON.parse(fileContent);
res.status(200).json({ places: placesData });
});
app.get("/user-places", async (req, res) => {
const fileContent = await fs.readFile("./data/user-places.json");
const places = JSON.parse(fileContent);
res.status(200).json({ places });
});
app.put("/user-places", async (req, res) => {
const placeId = req.body.placeId;
const fileContent = await fs.readFile("./data/places.json");
const placesData = JSON.parse(fileContent);
const place = placesData.find((place) => place.id === placeId);
const userPlacesFileContent = await fs.readFile("./data/user-places.json");
const userPlacesData = JSON.parse(userPlacesFileContent);
let updatedUserPlaces = userPlacesData;
if (!userPlacesData.some((p) => p.id === place.id)) {
updatedUserPlaces = [...userPlacesData, place];
}
await fs.writeFile(
"./data/user-places.json",
JSON.stringify(updatedUserPlaces)
);
res.status(200).json({ userPlaces: updatedUserPlaces });
});
app.delete("/user-places/:id", async (req, res) => {
const placeId = req.params.id;
const userPlacesFileContent = await fs.readFile("./data/user-places.json");
const userPlacesData = JSON.parse(userPlacesFileContent);
const placeIndex = userPlacesData.findIndex((place) => place.id === placeId);
let updatedUserPlaces = userPlacesData;
if (placeIndex >= 0) {
updatedUserPlaces.splice(placeIndex, 1);
}
await fs.writeFile(
"./data/user-places.json",
JSON.stringify(updatedUserPlaces)
);
res.status(200).json({ userPlaces: updatedUserPlaces });
});
// 404
app.use((req, res, next) => {
if (req.method === "OPTIONS") {
return next();
}
res.status(404).json({ message: "404 - Not Found" });
});
app.listen(3000);