Skip to content

Commit

Permalink
Aula4
Browse files Browse the repository at this point in the history
  • Loading branch information
leasampaio committed Apr 10, 2021
1 parent 33c3911 commit e398ebb
Show file tree
Hide file tree
Showing 15 changed files with 236 additions and 58 deletions.
48 changes: 48 additions & 0 deletions api/Serializar.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
const FormatoInvalido = require('./erros/Formatoinvalido');

class Serializar {
json (dados){
JSON.stringify(dados)
}
transformar(dados){
if(this.contentType !== 'application/json'){
throw new FormatoInvalido(this.contentType);

}
return this.json(this.filtrar(dados));
}
filtrarCampos (dados){
const camposFiltrados = {};
this.camposPermitidos.forEach(campo => {
if(dados.hasOwnProperty(campo)){
camposFiltrados[campo]= dados[campo];
}

});
}
filtrar(dados){
let dadosFiltrados = this.filtrarCampos(dados);

if(Array.isArray(dados)){
dadosFiltrados.map((dados)=>{
return this.filtrarCampos(dados);

})
}

return dadosFiltrados;
}
}

class SerializarAgendamento extends Serializar{
constructor(contentType, camposPersonalizados){
super()
this.contentType = contentType;
this.camposPermitidos = ['id', 'nome_cliente', 'data_agendamento'].concat(camposPersonalizados || [])
}
}
module.exports ={
Serializar: Serializar,
SerializarAgendamento: SerializarAgendamento,
FormatosValidos : ['application/json']
}
15 changes: 15 additions & 0 deletions api/agendamentos/Agendamento.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,21 @@ class Agendamento {

async remover() {
await TabelaAgendamento.remover(this.id)
}
async atualizar(){
await TabelaAgendamento.buscarPorPK(this.id)
const camposAtualizaveis = ['nome_cliente','nome_servico','status','data_agendamento']
const dadosAtualizar = {}
camposAtualizaveis.forEach((campo)=>{
const valor = this [campo];
if(typeof valor === 'string' && valor.length>0){
dadosAtualizar[campo]= valor;
}
})
await TabelaAgendamento.atualizar(this.id, dadosAtualizar )



}
}
module.exports = Agendamento;
64 changes: 64 additions & 0 deletions api/agendamentos/TabelaAgendamento.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
const { removeAllListeners } = require('nodemon');
const modeloAgendamento = require('./modelTabelaAgendamento');

module.exports = {
async listar() {
try{
return await modeloAgendamento.findAll({
raw: true,
});

}
catch(error){
throw error
}

},

async adicionar(agendamento) {
try{
return await modeloAgendamento.create(agendamento);
}
catch(error){
throw error
}

},

async buscarPorPK(id) {
try{
return await modeloAgendamento.findByPk(id);
}
catch(error){
throw error
}

},

async remover(id) {
try{
return await modeloAgendamento.destroy({
where: {
id: id
}
});
}
catch(error){
throw error
}

},
async atualizar (id, dados){
try{
return await modeloAgendamento. update(dados,
{where: {
id:id
}})

}
catch(error){
throw error
}

}
}
26 changes: 0 additions & 26 deletions api/agendamentos/TabelaAgendamentos.js

This file was deleted.

File renamed without changes.
16 changes: 15 additions & 1 deletion api/config/configExpress.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@
const express = require('express');
const router = require('../routes/agendamentos')
const router = require('../routes/agendamentos');
const FormatoInvalido = require ('../erros/Formatoinvalido');
const FormatosValidos = require('../Serializar').FormatosValidos;

module.exports =()=>{
const app = express()
app.use((req, resp, next) =>{
let formatoSolicitado = req.header('Accept');
if(formatoSolicitado === '*/*'){
formatoSolicitado = 'application/json'
}
if(FormatosValidos.indexOf(formatoSolicitado) === -1){
resp.status(406);
return resp.send();
}
resp.setHeader('Content-Type', formatoSolicitado);
next();
})
app.use(express.json())
app.use('/api', router)
return app
Expand Down
11 changes: 6 additions & 5 deletions api/db/criarTabela.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
const ModeloTabelaAgendamento = require('../agendamentos/TabelaAgendamentos');
const ModeloTabelaAgendamento = require('../agendamentos/modelTabelaAgendamento');

ModeloTabelaAgendamento.sync()
.then(()=>{
console.log('Tabela ciada com sucesso')
.then(()=> {
console.log('Tabela criada com sucesso')
})
.catch(
.catch(() => {
console.log('Erro, tabela não criada')
);
});
10 changes: 10 additions & 0 deletions api/erros/CampoQtMinima.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
class CampoQtdMinhima extends Error{
constructor(campo){
const mensagem = `O campo ${campo} tem que ter no mínimo 8 carcateres!`
super(mensagem);
this.name ='CampoQtdMinima';
this.idError = 2;

}
}
module.exports = CampoQtdMinhima;
10 changes: 10 additions & 0 deletions api/erros/CampoQtdMaxima.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
class CampoQtdMaxima extends Error{
constructor(campo){
const mensagem = `O campo ${campo} tem que ter no máximo 64 carcateres!`
super(mensagem);
this.name ='CampoQtdMaxima';
this.idError = 5;

}
}
module.exports = CampoQtdMaxima;
9 changes: 9 additions & 0 deletions api/erros/Campoinvalido.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class CampoInvalido extends Error {
constructor(campo){
const mensagem = `O campo ${campo} está inválido!`
super(mensagem);
this.name = 'CampoInvalido';
this.idError =1;
}
}
module.exports = CampoInvalido;
9 changes: 9 additions & 0 deletions api/erros/DadosNaoInformados.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class DadosNaoInformados extends Error {
constructor(){
super('Dados não informados');
this.name ='DadosNaoInformados';
this.idError = 3;

}
}
module.exports = DadosNaoInformados;
9 changes: 9 additions & 0 deletions api/erros/Formatoinvalido.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class FormatoInvalido extends Error{
constructor(contentType){
const mensagem = `O tipo ${contentType} é inválido! A API aceita somente JSON`
super(mensagem);
this.name = 'FormatoInvalido';
this.idError = 6;
}
}
module.exports = FormatoInvalido;
9 changes: 9 additions & 0 deletions api/erros/NaoEncontrado.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class NaoEncontrado extends Error{
constructor(agendamento){
super('O agendamento não foi encontrado!');
this.name = 'NaoEncontrado';
this.id = 4;

}
}
module.exports = NaoEncontrado;
34 changes: 32 additions & 2 deletions api/routes/agendamentos/index.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
const router = require('express').Router()
const TabelaAgendamento = require('../../agendamentos/TabelaAgendamento');
const Agendamento = require('../../agendamentos/Agendamento')
const SerializadorAgendamento = require('../../Serializar').SerializarAgendamento;

router.get('/agendamentos', async (req, resp) => {
const results = await TabelaAgendamento.listar()
resp.send(JSON.stringify(results));

const results = await TabelaAgendamento.listar()
const serializador = new SerializadorAgendamento(
resp.getHeader('Content-Type'),['nome_servico', 'status']
);
agendamentos = serializador.transformar(results)
resp.status(200).send(agendamentos);


});

router.post('/agendamentos', async (req, resp) => {
Expand Down Expand Up @@ -42,5 +50,27 @@ router.delete('/agendamentos/:idAgendamento', async (req, resp) => {
}))
}
});
router.put('/agendamentos/:idAgendamento', async (req, resp)=>{
try{

const id = req.params.idAgendamento;
const dadosBody = req.body;
const dados = Object.assign({}, dadosBody, {id: id})
const agendamento = new Agendamento(dados);
await agendamento.atualizar();

resp.send(JSON.stringify({
mensagem:'Registro atualizado'
})
);


}
catch (error){
resp.send(JSON.stringify({
mensagem: error.message
}))
}
});

module.exports = router
24 changes: 0 additions & 24 deletions desafio.js

This file was deleted.

0 comments on commit e398ebb

Please sign in to comment.