-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
93 lines (61 loc) · 1.73 KB
/
Copy pathserver.js
File metadata and controls
93 lines (61 loc) · 1.73 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
const express = require('express');
const path = require('path');
const fs = require('fs');
const notes = require('./db/db.json')
const uuid = require('./uuid')
const PORT = process.env.PORT || 3001;
const app = express();
app.use(express.json());
app.use(express.static('public'));
app.get('/notes', (req, res) =>
res.sendFile(path.join(__dirname, 'public/notes.html'))
);
app.get('/api/notes', (req, res) => {
fs.readFile('./db/db.json', 'utf8', (err, notes) => {
if (err) {
console.error(err);
} else {
return res.json(JSON.parse(notes));
}
})
});
app.post('/api/notes', (req, res) => {
console.info(`${req.method} request received to add a review`);
const { title, text } = req.body;
if (title && text) {
const newTip = {
title,
text,
text_id: uuid(),
};
fs.readFile('./db/db.json', 'utf8', (err, data) => {
if (err) {
console.error(err);
} else {
const parsedReviews = JSON.parse(data);
parsedReviews.push(newTip);
fs.writeFile(
'./db/db.json',
JSON.stringify(parsedReviews, null, 4),
(writeErr) =>
writeErr
? console.error(writeErr)
: console.info('Successfully updated reviews!')
);
}
});
const response = {
status: 'success',
body: newTip,
};
res.status(201).json(response);
} else {
res.status(500).json('Error in posting review');
}
});
app.get('*', (req, res) =>
res.sendFile(path.join(__dirname, 'public/index.html'))
);
app.listen(PORT, () =>
console.log(`App listening at http://localhost:${PORT} 🚀`)
);