Created
November 18, 2019 18:41
-
-
Save johnnyferreiradev/033e34ed855b66aa4ba13e5521478627 to your computer and use it in GitHub Desktop.
Minha solução para o desafio 01 do Bootcamp GoStack 2019
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const server = express(); | |
server.use(express.json()); | |
// Banco de dados | |
const projects = []; | |
let reqNumber = 0; | |
// Middlewares | |
server.use((req, res, next) => { | |
reqNumber++; | |
console.log("Quantidade de requisições feitas = " + reqNumber); | |
return next(); | |
}); | |
function checkProjectExists(req, res, next) { | |
const { id } = req.params; | |
projects.forEach((project) => { | |
if(project.id === id) { | |
return next(); | |
} | |
}); | |
return res.status(400).json({ error: 'User not found' }); | |
} | |
// Rotas | |
server.post('/projects', (req, res) => { | |
projects.push(req.body); | |
return res.json(projects); | |
}); | |
server.get('/projects', (req, res) => { | |
return res.send(projects); | |
}); | |
server.put('/projects/:id', checkProjectExists, (req, res) => { | |
const { id } = req.params; | |
const { title } = req.body; | |
projects.forEach((project) => { | |
if(project.id === id) { | |
project.title = title; | |
} | |
}); | |
return res.json(projects); | |
}); | |
server.delete('/projects/:id', checkProjectExists, (req, res) => { | |
const { id } = req.params; | |
projects.forEach((project, index) => { | |
if(project.id === id) { | |
projects.splice(index, 1); | |
} | |
}); | |
return res.send(); | |
}); | |
server.post('/projects/:id/tasks', checkProjectExists, (req, res) => { | |
const { id } = req.params; | |
const { title } = req.body; | |
projects.forEach((project) => { | |
if(project.id === id) { | |
project.tasks.push(title); | |
} | |
}); | |
return res.json(projects); | |
}); | |
// Server | |
server.listen(3000, () => { | |
console.log('Servidor em execussão na porta 3000'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment