-
Notifications
You must be signed in to change notification settings - Fork 0
/
01final.js
79 lines (57 loc) · 1.67 KB
/
01final.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
79
const express = require('express');
const server = express();
server.use(express.json());
// Query params = ?teste=1
// Route params = /users/1
// Request body = { "name": "Arthur", "email": "kaakk@kakak.kaak.ka" }
const users = ['Diegão', 'Cláudio', 'Victor'];
//////// esse middleware faz um log depois de cada aquisição
// MIDDLEWARE GLOBAL //
server.use((req, res, next) => {
console.log(`Método: ${req.method}; URL: ${req.url}`);
return next();
console.timeEnd('Request');
});
//// middleware local ////
function checkUserExists(req, res, next) {
if (!req.body.name) {
return res.status(400).json({ error: 'User name is required' });
}
return next();
}
// middleware check user array
function checkUserInArray(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.get('/users', (req, res) => {
return res.json(users);
})
server.get('/users/:index', checkUserInArray, (req, res) => {
const { index } = req.params;
//return res.json(users[index]);
return res.json(req.user);
})
// with middleware local
server.post('/users', checkUserExists, (req, res) => {
const { name } = req.body;
users.push(name);
return res.json(users);
});
// with middleware local
server.put('/users/:index', checkUserExists, checkUserInArray, (req, res) => {
const { index } = req.params;
const { name } = req.body;
users[index] = name;
return res.json(users);
});
server.delete('/users/:index', checkUserInArray, (req, res) => {
const { index } = req.params;
users.splice(index, 1);
return res.send();
});
server.listen(3000);