-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
73 lines (48 loc) · 1.28 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
70
71
72
73
const express = require('express')
const server = express()
server.use(express.json())
const users = []
server.use((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: 'User name is required' })
}
return next()
}
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 { user } = req
return res.json(user)
})
server.post('/users', checkNameExists, (req, res) => {
const { name } = req.body
users.push(name)
return res.json(users)
})
server.put('/users/:index', checkUserInArray, checkNameExists, (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)