-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
85 lines (57 loc) · 1.6 KB
/
server.js
File metadata and controls
85 lines (57 loc) · 1.6 KB
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
var express = require("express");
var path = require("path");
var fs = require("fs");
var notes = require("./db/db.json")
var app = express();
var PORT = process.env.PORT || 8080;
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
currentID = notes.length;
// API Routes
app.get("/api/notes", function (req, res) {
return res.json(notes);
});
app.post("/api/notes", function (req, res) {
var newNote = req.body;
newNote["id"] = currentID +1;
currentID++;
console.log(newNote);
notes.push(newNote);
rewriteNotes();
return res.status(200).end();
});
app.delete("/api/notes/:id", function (req, res) {
res.send('Got a DELETE request at /api/notes/:id')
var id = req.params.id;
var idLess = notes.filter(function (less) {
return less.id < id;
});
var idGreater = notes.filter(function (greater) {
return greater.id > id;
});
notes = idLess.concat(idGreater);
rewriteNotes();
})
// Access files in "public" folder
app.use(express.static("public"));
// HTML Routes
app.get("/notes", function (req, res) {
res.sendFile(path.join(__dirname, "public/notes.html"));
});
app.get("*", function (req, res) {
res.sendFile(path.join(__dirname, "public/index.html"));
});
// Listen
app.listen(PORT, function () {
console.log("App listening on PORT " + PORT);
});
// Functions
function rewriteNotes() {
fs.writeFile("db/db.json", JSON.stringify(notes), function (err) {
if (err) {
console.log("error")
return console.log(err);
}
console.log("Success!");
});
}