-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
69 lines (51 loc) · 1.41 KB
/
index.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
const express = require('express');
const server = express();
server.use(express.json());
// Middlewares
function log(req, res, next) {
console.time('Request');
console.log(`Method: ${req.method}; URL: ${req.url};`);
next();
console.timeEnd('Request');
}
function CheckNameExists(req, res, next) {
if(!req.body.name) {
return res.status(400).json({ error: 'Name is required' });
}
next();
}
function CheckUserExists(req, res, next) {
const user = users[req.params.index];
if(!user) {
return res.status(400).json({ error: 'User does not exists' });
}
req.user = user;
return next();
}
server.use(log);
const users = ['Diego', 'HermersonDev'];
server.get('/users', (req, res) => {
return res.json(users);
});
server.get('/users/:index', CheckUserExists, (req, res) => {
return res.json(req.user);
});
server.post('/users', CheckNameExists, (req, res) => {
const { name } = req.body;
users.push(name);
return res.json(users);
});
server.put('/users/:index', CheckNameExists, CheckUserExists, (req, res) => {
const { name } = req.body;
const { index } = req.params;
users[index] = name;
return res.json(users);
});
server.delete('/users/:index', CheckUserExists, (req, res) => {
const { index } = req.params;
users.splice(index, 1);
return res.send();
});
server.listen(3000, () => {
console.log('server on');
});