-
Notifications
You must be signed in to change notification settings - Fork 2
/
use_an_express_router.js
67 lines (56 loc) · 1.85 KB
/
use_an_express_router.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
const express = require('express');
const { seedElements, getElementById, createElement, updateElement, getIndexById } = require('./utils');
let expressions = [];
seedElements(expressions, 'expressions');
const expressionsRouter = express.Router();
// Get all expressions
expressionsRouter.get('/', (req, res, next) => {
res.send(expressions);
});
expressionsRouter.get('/:id', (req, res, next) => {
const expression = expressions[req.params.id];
if (expression) {
res.status(200).send(expression);
} else {
res.status(404).send();
}
});
expressionsRouter.get('/:id', (req, res, next) => {
const thisexpression = getElementById(req.params.id, expressions);
if (thisexpression) {
res.send(thisexpression);
} else {
res.status(404).send("Not found");
}
});
// Update/PUT
expressionsRouter.put('/:id', (req, res, next) => {
const updatesToApply = req.query;
if (expressions[req.params.id]) {
const thisexpression = updateElement(req.params.id, updatesToApply, expressions);
res.send(thisexpression);
} else {
res.status(404).send("Not found");
}
});
// Create/POST
expressionsRouter.post('/', (req, res, next) => {
const newexpression = createElement('expressions', req.query);
if (newexpression) {
expressions.push(newexpression);
res.status(201).send(newexpression);
} else {
res.status(400).send("Couldn't create the object with the parameters provided");
}
});
// Delete/DELETE
expressionsRouter.delete('/:id', (req, res, next) => {
const expressionIndex = getIndexById(req.params.id, expressions);
if (expressionIndex != -1) {
expressions.splice(expressionIndex, 1);
res.status(204).send(expressions[expressionIndex]);
} else {
res.status(404).send();
}
});
module.exports = expressionsRouter;