-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
78 lines (68 loc) · 1.49 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 modules
let express = require("express");
let app = express();
let parser = require('body-parser');
// import NeDB database
const db = require('./store');
// to support JSON-encoded bodies.
app.use(parser.json());
// to support URL-encoded bodies
app.use(parser.urlencoded({
extended: true
}));
// GET
app.get("/api", (req, res) => {
db.find({}, (err, resp) => {
if (err) {
console.log(err);
} else
res.json(resp);
});
});
// POST
app.post('/api', (req, res) => {
db.insert(req, (err, resp) => {
if (err) {
console.log(err);
} else
res.json(resp);
});
});
// GET (view / edit)
app.get('/api/:id', (req, res) => {
db.findOne({_id: req.params.id}, {}, (resp, err) => {
if (err) {
console.log(err);
} else
res.json(resp);
});
});
// PUT (single)
app.put('/api/:id', (req, res) => {
db.update({_id: req.params.id}, {$set: req.body}, (err, numReplaced) => {
if (err) {
console.log(err);
} else
res.json(numReplaced);
});
});
// DELETE (single)
app.delete('/api/:id', (req, res) => {
db.remove({_id: req.params.id}, {}, (err, resp) => {
if (err) {
console.log(err);
} else
res.json(resp);
});
});
// DELETE (all)
app.delete('/api', (req, res) => {
db.remove({}, {multi: true}, (err, numRemoved) => {
if (err) {
console.log(err);
} else
res.json(numRemoved);
});
});
// set app port for connections to listen
app.listen(4500, () => console.log('Listening on port 4500'));