-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
117 lines (79 loc) · 2.37 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
const express = require('express')
const server = express()
server.use(express.json())
const projects = []
let count = 0
function getErrorMessage(res, errors) {
return res.status(400).json({ errors })
}
function verifyProperty(body, propName) {
const prop = body[propName]
if (!prop) {
return `Property "${propName}" is required`
}
if (typeof(prop) != 'string') {
return `Property type "${propName}" must be string`
}
}
function verifyProperties(body, properties) {
const errors = []
properties.forEach(prop => {
const error = verifyProperty(body, prop)
if (error) {
errors.push(error)
}
});
return errors
}
function countRequisition(req, res, next) {
count++
next()
console.log(`Requisition(s): ${count}`)
}
function verifyAllProjectProperties(req, res, next) {
const errors = verifyProperties(req.body, ['id', 'title'])
if (errors.length > 0)
return getErrorMessage(res, errors)
next()
}
function verifyTitleProperty(req, res, next) {
const errors = verifyProperties(req.body, ['title'])
if (errors.length > 0)
return getErrorMessage(res, errors)
next()
}
function verifyIfProjectExists(req, res, next) {
const { id } = req.params
if (!id)
return getErrorMessage(res, ['Parameter id is required'])
const index = projects.findIndex(item => item.id === id)
if (index === -1)
return getErrorMessage(res, [`Project does not exists`])
req.projectIndex = index
next()
}
server.post('/projects', countRequisition, verifyAllProjectProperties, (req, res) => {
const { id, title } = req.body
projects.push({
id, title, tasks: []
})
return res.json(projects)
})
server.put('/projects/:id', countRequisition, verifyIfProjectExists, verifyTitleProperty, (req, res) => {
const { title } = req.body
projects[req.projectIndex].title = title
return res.json(projects[req.projectIndex])
})
server.put('/projects/:id/tasks', countRequisition, verifyIfProjectExists, verifyTitleProperty, (req, res) => {
const { title } = req.body
projects[req.projectIndex].tasks.push(title)
return res.json(projects[req.projectIndex])
})
server.delete('/projects/:id', countRequisition, verifyIfProjectExists, (req, res) => {
projects.splice(req.projectIndex, 1)
return res.send()
})
server.get('/projects', countRequisition, (req, res) => {
return res.json(projects)
})
server.listen(3000)