-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
78 lines (67 loc) · 2.2 KB
/
index.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
// Express framework to write end points and middleware
const express = require("express");
const app = express();
const port = process.env.PORT || 3000;
// File Sync library to write to the local json
const fs = require("fs");
// Local json storage file which will mock a db
const storage = "storage.json";
// Recoginizes the incoming Request Object as a JSON; Middleware
app.use(express.json());
// Middleware to that will log the date whenever a request happens
app.use((req, res, next) => {
let date = new Date();
console.log(date.toLocaleTimeString());
next();
});
// Add a callback for route parameters
app.param("school", (req, res, next, school) => {
if (school.toLowerCase() == "vanderbilt") {
req.school = "vanderbilt";
next();
} else {
next(Error("Invalid School"));
}
});
// Root route
app.get("/", (req, res) => {
res.status(200).send("Root route");
});
// Route that will use the school parameter we set up
app.get("/:school", (req, res, next) => {
// Reads the file
fs.readFile(storage, (err, data) => {
if (err) {
next(err);
} else {
let school = JSON.parse(data);
let info = school.vanderbilt;
console.log(school);
res.status(200).json(info);
}
});
});
// Route that will post information to a specific school's section in the JSON file
app.post("/vanderbilt", (req, res, next) => {
let schoolName = req.school;
fs.readFile(storage, (err, data) => {
if (err) {
next(err);
}
let newLocation = req.body.location;
let newUndergrad = req.body.undergrad;
let school = JSON.parse(data);
school.vanderbilt.location = newLocation;
school.vanderbilt.undergrad = newUndergrad;
json = JSON.stringify(school);
fs.writeFileSync(storage, json);
res.status(200).send("Post successful");
});
});
// Middleware that will handle errors that get thrown
app.use((err, req, res, next) => {
console.log(err.stack);
res.status(500).send(err.message);
});
// Starts the express server to listen on the port provided
app.listen(port, () => console.log(`App is listening on port ${port}`));