-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
103 lines (83 loc) · 2.52 KB
/
Copy pathserver.js
File metadata and controls
103 lines (83 loc) · 2.52 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
const express = require('express');
const path = require('path');
const fs = require('fs');
const uniqid = require('uniqid');
let textSaved = require('./db/db.json');
const PORT = process.env.PORT || 3001;
const app = express();
// Middleware for parsing JSON and urlencoded form data
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));
app.get('/notes', (req, res) => {
res.sendFile(path.join(__dirname, '/public/notes.html'))
}
);
app.get('/api/notes', (req, res) => {
res.json(textSaved);
})
// saves the notes
app.post('/api/notes', (req, res) => {
// Destructuring assignment for the items in req.body
const { title, text } = req.body;
if (title && text) {
const newNote = {
title,
text,
id: uniqid(),
};
fs.readFile('./db/db.json', 'utf8', (err, data) => {
if (err) {
console.error(err);
}
else {
const parsedSaved = JSON.parse(data);
parsedSaved.push(newNote);
textSaved = parsedSaved;
fs.writeFile(
'./db/db.json',
JSON.stringify(parsedSaved, null, 3),
(writeErr) =>
writeErr
? console.error(writeErr)
: console.info('Successfully added note!')
);
}
res.json(textSaved);
}
)
}
})
app.delete('/api/notes/:id', (req, res) => {
let currentId = req.params.id;
fs.readFile('./db/db.json', 'utf8', (err, data) => {
if (err) {
console.error(err);
}
else {
const parsedSaved = JSON.parse(data);
for (let i = 0; i < parsedSaved.length; i++) {
if (currentId == parsedSaved[i].id) {
parsedSaved.splice(i, 1);
}
}
textSaved = parsedSaved;
fs.writeFile(
'./db/db.json',
JSON.stringify(parsedSaved),
(writeErr) =>
writeErr
? console.error(writeErr)
: console.info('Successfully deleted!')
);
}
res.json(textSaved);
}
)
})
app.get(`*`, (req, res) =>
res.sendFile(path.join(__dirname, '/public/index.html'))
);
app.listen(PORT, () =>
console.log(`App listening at http://localhost:${PORT} 🚀`)
);