-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
82 lines (57 loc) · 1.56 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
const express = require('express');
const server = express();
server.use(express.json());
let reqCounts = 0;
const projects = [
{
id: "1",
title: "Projeto NodeJS",
tasks: ["Instalar Ambiente", "Configura Projeto"]
},
{
id: "2",
title: "Projeto ReactJS",
tasks: ["Configurar VSCode", "Rodar Demo"]
}
];
server.use((req, res, next) => {
reqCounts++;
next();
console.log(`Quantidade de Requisições: ${reqCounts}`);
})
function checkProjectInArray(req, res, next) {
const index = projects.findIndex(x => x.id === req.params.id);
const project = projects[index];
if (!project) {
return res.status(400).json({ error: 'Project does not exists' });
}
req.project = project;
req.index = index;
return next();
}
server.get('/projects', (req, res) => {
return res.json(projects);
})
server.get('/projects/:id', checkProjectInArray, (req, res) => {
return res.json(req.project);
})
server.post('/projects', (req, res) => {
const { project} = req.body;
projects.push(project);
return res.json(projects);
})
server.put('/projects/:id', checkProjectInArray, (req, res) => {
const { title } = req.body.project;
projects[req.index].title = title;
return res.json(projects);
})
server.delete('/projects/:id', checkProjectInArray, (req, res) => {
projects.splice(req.index, 1);
return res.send();
})
server.post('/projects/:id/tasks', checkProjectInArray, (req, res) => {
const { title } = req.body;
projects[req.index].tasks.push(title);
return res.json(projects[req.index]);
})
server.listen(3000);