-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
86 lines (60 loc) · 2.06 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
// Require packages
const express = require("express");
const path = require("path");
const fs = require("fs");
const { request } = require("http");
// Initialize app, port, and root
const app = express();
const PORT = process.env.PORT || 3001;
const root = path.join(__dirname, "/public");
// Middleware
app.use(express.json());
app.use(express.static('public'));
app.use(express.urlencoded({extended: true}));
// Route for user to take notes
app.get("/notes", (req, res) => {
res.sendFile(path.join(root, "notes.html"));
});
// Custom API route
app.get("/api/notes", (req, res) => {
res.sendFile(path.join(__dirname, "/db/db.json"));
});
// API route for notes per id
app.get("/api/notes/:id", (req, res) => {
let savedNotes = JSON.parse(fs.readFileSync("./db/db.json", "utf8"));
res.json(savedNotes[Number(req.params.id)]);
});
// Root route
app.get("*", (req, res) => {
res.sendFile(path.join(root, "index.html"));
});
// POST requesest, add new note and object in database
app.post("/api/notes", (req, res) => {
let savedNotes = JSON.parse(fs.readFileSync("./db/db.json", "utf8"));
let newNote = req.body;
let uniqueID = (savedNotes.length).toString();
newNote.id = uniqueID;
savedNotes.push(newNote);
fs.writeFileSync("./db/db.json", JSON.stringify(savedNotes));
console.log("A new note has been saved: ", newNote);
res.json(savedNotes);
})
// DELETE request, delete note and object in database
app.delete("/api/notes/:id", (req, res) => {
let savedNotes = JSON.parse(fs.readFileSync("./db/db.json", "utf8"));
let noteID = req.params.id;
let newID = 0;
console.log(`Note ID ${noteID} has been deleted.`) ;
savedNotes = savedNotes.filter(currentNote => {
return currentNote.id != noteID;
})
for (currentNote of savedNotes) {
currentNote.id = newID.toString();
newID++;
}
fs.writeFileSync("./db/db.json", JSON.stringify(savedNotes));
res.json(savedNotes);
})
app.listen(PORT, () => {
console.log(`Application lauched at ${PORT}. Enjoy your stay!`);
})