-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
242 lines (222 loc) · 6.46 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
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
const express = require("express");
const app = express();
const port = 3000;
const path = require("path");
const fs = require("fs");
const Ajv = require("ajv");
const ajv = new Ajv();
const carSchema = require("./schema/carSchema.js");
const driverSchema = require("./schema/driverSchema.js");
const { exec } = require("child_process");
const cors = require('cors');
//Middleware for express
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname)));
app.use(express.json());
//GET google map
app.get("/", function (req, res) {
res.render("index");
});
//GET sight nearby depending on current user
app.get("/sight", function (req, res) {
//read json file and parse data
fs.readFile("data/currSightsReq.json", "utf-8", (err, data) => {
if (err) throw err;
var obj = JSON.parse(data);
res.status(200).json(obj);
});
});
//GET all cars
app.get("/car", function (req, res) {
//read json file if exists and parse data
if (fs.existsSync("data/car.json")) {
fs.readFile("data/car.json", "utf-8", (err, data) => {
if (err) {
throw err;
}
var obj = JSON.parse(data);
res.status(200).json(obj);
});
} else {
res.status(404).json({ status: "No cars available" });
}
});
//GET one specific car
app.get("/car/:id", async function (req, res) {
try {
//read json file async and parse data
const data = await fs.promises.readFile("data/car.json", "utf8");
const cars = JSON.parse(data);
//search for matched car
const car = Object.entries(cars).find(
([key, value]) => key == req.params.id
);
if (!car) {
res.status(404).send("Car not found.");
} else {
//return matched car
res.json(car[1]);
}
} catch (err) {
res.status(500).send(`Error reading cars.json file: ${err}`);
}
});
//DELETE all cars
app.delete("/car", function (req, res) {
//delete json file
fs.unlink("data/car.json", (err) => {
if (err) {
throw err;
}
res.status(200).json({ status: "Succesfully deleted" });
});
});
//POST new car
app.post("/car", function (req, res) {
//validate with carschema
const validate = ajv.compile(carSchema);
const valid = validate(req.body);
if (!valid) {
res.status(400).send(validate.errors);
} else {
// Check if the json file exists
fs.access("data/car.json", fs.constants.F_OK, (err) => {
let jsonData = {};
if (!err) {
// Read the json file
fs.readFile("data/car.json", "utf8", (err, data) => {
if (err) {
console.log(err);
}
if (data) {
jsonData = JSON.parse(data);
}
// Append the new car object to the existing data object
jsonData = { ...jsonData, [req.body.carId]: req.body };
// Write the updated data object to the json file
fs.writeFile("data/car.json", JSON.stringify(jsonData), (err) => {
if (err) {
console.log(err);
}
res.send("Object added successfully");
});
});
} else {
jsonData = { [req.body.carId]: req.body };
// Write the new data object to the json file
fs.writeFile("data/car.json", JSON.stringify(jsonData), (err) => {
if (err) {
console.log(err);
}
res.send("Object added successfully");
});
}
});
}
});
//POST new driver
app.post("/driver", function (req, res) {
//validate with driverSchema
const validate = ajv.compile(driverSchema);
const valid = validate(req.body);
if (!valid) {
res.status(400).send(validate.errors);
} else {
// Check if the json file exists
fs.access("data/driver.json", fs.constants.F_OK, (err) => {
let jsonData = {};
if (!err) {
// Read the json file
fs.readFile("data/driver.json", "utf8", (err, data) => {
if (err) {
console.log(err);
}
if (data) {
jsonData = JSON.parse(data);
}
// Append the new driver object to the existing data object
jsonData = { ...jsonData, [req.body.driverId]: req.body };
// Write the updated data object to the json file
fs.writeFile("data/driver.json", JSON.stringify(jsonData), (err) => {
if (err) {
console.log(err);
}
res.send("Object added successfully");
});
});
} else {
jsonData = { [req.body.driverId]: req.body };
// Write the new data object to the json file
fs.writeFile("data/driver.json", JSON.stringify(jsonData), (err) => {
if (err) {
console.log(err);
}
res.send("Object added successfully");
});
}
});
}
});
//GET all driver
app.get("/driver", function (req, res) {
//read json file if exists and parse data
if (fs.existsSync("data/driver.json")) {
fs.readFile("data/driver.json", "utf-8", (err, data) => {
if (err) {
throw err;
}
var obj = JSON.parse(data);
res.status(200).json(obj);
});
} else {
res.status(404).json({ status: "No driver available" });
}
});
//GET one specific driver
app.get("/driver/:id", async function (req, res) {
try {
//read json file async and parse data
const data = await fs.promises.readFile("data/driver.json", "utf8");
const drivers = JSON.parse(data);
//search for matched driver
const driver = Object.entries(drivers).find(
([key, value]) => key == req.params.id
);
if (!driver) {
res.status(404).send("Driver not found.");
} else {
//return driver
res.json(driver[1]);
}
} catch (err) {
res.status(500).send(`Error reading driver.json file: ${err}`);
}
});
//DELETE all driver
app.delete("/driver", function (req, res) {
//delete json file
fs.unlink("data/driver.json", (err) => {
if (err) {
throw err;
}
res.status(200).json({ status: "Succesfully deleted" });
});
});
//EXECUTE script for calculation
app.get("/insertData/:id", (req, res) => {
let id = req.params.id;
exec("npm run start " + id, (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return res.status(500).send(error.message);
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return res.status(500).send(stderr);
}
res.status(200).send("Script executed successfully");
});
});
//Server listen on port 3000
app.listen(port);
console.log(`App listen on port ${port}`);