-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
124 lines (94 loc) · 2.43 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
118
119
120
121
122
123
124
const express = require('express');
const server = express();
/* Add JSON Support for HTTP requests */
server.use(express.json());
let projects = [{
id: 1,
title: 'Node.js',
tasks: []
}];
const fieldsRequired = ['id', 'title', 'tasks'];
/* Helpers */
function findProject(req) {
const { id } = req.params;
return projects.find(p => p.id == id);
}
/* Validation Middleware's */
function checkProjectExists(req, res, next) {
var project = findProject(req);
if ( !project ) {
return res.status(400).json({
status: 'error',
msg: 'Project does not exists'
});
}
return next();
}
function payloadRequired(req, res, next) {
fieldsRequired.map((field) => {
if ( !req.body[field] ) {
return res.json({
status: 'error',
msg: `${field} is required`
})
}
});
return next();
}
/* Request Counter Middleware */
function reqCounter(req, res, next) {
console.count('Requisições feitas: ');
return next();
}
/* Global use Request Counter middleware */
server.use(reqCounter);
server.get('/projects', (req, res) => {
return res.json({
status: 'success',
projects
});
});
server.get('/projects/:id', checkProjectExists, (req, res) => {
const project = findProject(req);
return res.json({
status: 'success',
project
});
});
server.post('/projects', payloadRequired, (req, res) => {
projects.push(req.body);
return res.json({
status: 'success',
projects
});
});
server.put('/projects/:id', checkProjectExists, payloadRequired, (req, res) => {
const { title } = req.body;
let project = findProject(req);
let idx = projects.indexOf(project);
project.title = title;
projects[idx] = project;
return res.json({
status: 'success',
project
});
});
server.delete('/projects/:id', checkProjectExists, (req, res) => {
const { id } = req.params;
const idx = projects.findIndex(p => p.id == id);
projects.splice(idx, 1);
return res.json({
status: 'success'
});
});
server.post('/projects/:id/tasks', checkProjectExists, (req, res) => {
const { title } = req.body;
const project = findProject(req);
project.tasks.push(title);
return res.json({
status: 'success',
project
});
});
/* Running HTTP server */
server.listen(3000);