-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
78 lines (57 loc) · 1.88 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
import express from "express";
import cors from "cors";
import fs from "fs";
import path from "path";
const app = express();
const port = 3000;
const __dirname = path.resolve(path.dirname(""));
app.use(express.static("public"));
app.use(express.json());
app.use(cors());
app.get("/", (_req, res, _next) => {
console.log(__dirname);
res.sendFile(path.join(__dirname, "public", "index.html"));
});
app.get("/get-notes", (_req, res, _next) => {
fs.readFile("notes.json", "utf-8", (_err, data) => {
res.json(data);
});
});
app.post("/create-note", (req, res, next) => {
function generateUID() {
let uid = 0;
for (let i = 0; i < 8; i++) {
uid += (Math.floor(Math.random() * 10) * (10 ** i));
}
return uid;
}
let notes = JSON.parse(fs.readFileSync("notes.json").toString());
let newNote = {
id: generateUID(),
dateCreated: Date.now(),
dateLastEdited: Date.now(),
text: req.body.text
}
notes.notes.push(newNote);
fs.writeFileSync("notes.json", JSON.stringify(notes));
res.sendStatus(204);
});
app.post("/edit-note", (req, res, next) => {
let notes = JSON.parse(fs.readFileSync("notes.json").toString());
let editedNote = notes.notes.map(note => {
if (note.id === req.body.noteId) {
note.text = req.body.text;
}
return note;
});
fs.writeFileSync("notes.json", JSON.stringify({notes: editedNote }));
res.sendStatus(204);
});
app.post("/delete-note", (req, res, next) => {
let notes = JSON.parse(fs.readFileSync("notes.json").toString());
let deletedNote = notes.notes.filter(note => note.id !== req.body.noteId);
console.log(deletedNote);
fs.writeFileSync("notes.json", JSON.stringify({notes: deletedNote }));
res.sendStatus(204);
});
app.listen(port, () => console.log("Server running on port " + port));