-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
74 lines (62 loc) · 2 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
//When note is entered and saved, an object of "note title" and "note content" is saved to db.json
//First, we must read the db.json file (and parse)
//Then we have to push the new object into the db array
//Then we have to stringify and write it to the db.json
//When the note is saved, send it as a response to the front end
//
const express = require('express');
const path = require('path');
const {readFromFile, writeToFile, readAndAppend} = require('./helpers/fsUtils')
const { v4: uuidv4 } = require('uuid');
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'));
// GET Route for homepage
app.get('/', (req, res) =>
res.sendFile(path.join(__dirname, '/public/index.html'))
);
// GET Route for notes page
app.get('/notes', (req, res) => {
res.sendFile(path.join(__dirname, '/public/notes.html'));
});
// GET Route for notes api data
app.get('/api/notes', (req, res) => {
readFromFile('./db/db.json').then((data) => res.json(JSON.parse(data)))
})
// POST Route for notes api data
app.post('/api/notes', (req, res) => {
const {title, text} = req.body
if(title && text){
const newNote = {
title,
text,
id: uuidv4()
};
readAndAppend(newNote, './db/db.json');
const response = {
status: 'success',
body: newNote,
};
res.json(response);
} else {
res.json('Error in posting feedback');
}
}
);
// DELETE route for notes api data w/ specific id
app.delete('/api/notes/:id', (req, res) => {
const {id} = req.params;
readFromFile('./db/db.json').then((data)=> {
const parsedData = JSON.parse(data)
const noteIndex = parsedData.findIndex(note => note.id === id);
parsedData.splice(noteIndex, 1);
writeToFile('./db/db.json', parsedData);
return res.json(parsedData);
})
})
app.listen(PORT, () =>
console.log(`App listening at http://localhost:${PORT} 🚀`)
);