Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 14 additions & 14 deletions src/app.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import parser from 'body-parser';
import cors from 'cors';
import express from 'express';
import rateLimit from 'express-rate-limit';
// import rateLimit from 'express-rate-limit';
import helmet from 'helmet';
import morgan from 'morgan';
import swaggerUi from 'swagger-ui-express';
Expand Down Expand Up @@ -57,21 +57,21 @@ app.use(helmet({
app.use(cors());

// Rate limiting
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 500, // Limit each IP to 100 requests per windowMs
message: {
error: {
code: 429,
message: 'Muitas requisições. Tente novamente em 15 minutos.',
},
},
standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
legacyHeaders: false, // Disable the `X-RateLimit-*` headers
});
// const limiter = rateLimit({
// windowMs: 15 * 60 * 1000, // 15 minutes
// max: 500, // Limit each IP to 100 requests per windowMs
// message: {
// error: {
// code: 429,
// message: 'Muitas requisições. Tente novamente em 15 minutos.',
// },
// },
// standardHeaders: true, // Return rate limit info in the `RateLimit-*` headers
// legacyHeaders: false, // Disable the `X-RateLimit-*` headers
// });

// Apply rate limiting to all requests
app.use(limiter);
// app.use(limiter);

app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
app.use(parser.json());
Expand Down
10 changes: 7 additions & 3 deletions src/controllers/cidades-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@ import { Op } from 'sequelize';
import pick from '~/helpers/pick';

import BadRequestException from '../errors/bad-request-exception';
import limparEspacos from '../helpers/limpa-espaco';
import models from '../models';
import codigos from '../resources/codigos-http';
import verifyRecaptcha from '../utils/verify-recaptcha';

const { Cidade, LocalColeta, Tombo, Reino, Familia, Subfamilia, Genero, Especie, Subespecie, Variedade, sequelize } = models;

export const cadastrarCidade = (req, res, next) => {
const { nome, estado_id: estadoId, latitude, longitude } = req.body;

let { nome, estado_id: estadoId, latitude, longitude } = req.body;
nome = limparEspacos(nome);
const callback = async transaction => {
const cidadeEncontrada = await Cidade.findOne({
where: { nome, estado_id: estadoId },
Expand Down Expand Up @@ -47,7 +48,10 @@ export const cadastrarCidade = (req, res, next) => {
export const atualizarCidade = async (req, res, next) => {
try {
const { cidadeId } = req.params;
const dados = pick(req.body, ['nome', 'estado_id', 'latitude', 'longitude']);
let dados = pick(req.body, ['nome', 'estado_id', 'latitude', 'longitude']);
if (dados.nome) {
dados.nome = limparEspacos(dados.nome);
}
const cidadeAtual = await Cidade.findOne({ where: { id: cidadeId } });
if (!cidadeAtual) {
return res.status(404).json({
Expand Down
55 changes: 27 additions & 28 deletions src/controllers/coletor-controller.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,26 @@
import BadRequestException from '../errors/bad-request-exception';
import limparEspacos from '../helpers/limpa-espaco';
import models from '../models';
import codigos from '../resources/codigos-http';

const { Coletor, Sequelize: { Op } } = models;

export const cadastraColetor = async (req, res, next) => {
try {
if (req.body.nome) req.body.nome = limparEspacos(req.body.nome);

const coletor = await Coletor.create(req.body);

res.status(codigos.CADASTRO_RETORNO).json(coletor);
} catch (error) {
next(error);
}

return null;
};

export const encontraColetor = async (req, res, next) => {
try {
const { id } = req.params;
const coletor = await Coletor.findOne({
where: { id },
});
const coletor = await Coletor.findOne({ where: { id } });

if (!coletor) {
return res.status(404).json({ mensagem: 'Coletor não encontrado.' });
Expand All @@ -31,20 +30,22 @@ export const encontraColetor = async (req, res, next) => {
} catch (error) {
next(error);
}

return null;
};

export const listaColetores = async (req, res, next) => {
try {
const { id, nome } = req.query;
const { id } = req.query;
let { nome } = req.query;

const { limite, pagina } = req.paginacao;
const offset = (pagina - 1) * limite;

const where = {};

if (id) {
where.id = id;
} else if (nome) {
nome = limparEspacos(nome);
where.nome = { [Op.like]: `%${nome}%` };
}

Expand All @@ -55,16 +56,14 @@ export const listaColetores = async (req, res, next) => {
offset,
});

const response = {
res.status(200).json({
metadados: {
total: result.count,
pagina,
limite,
},
coletores: result.rows,
};

res.status(200).json(response);
});
} catch (error) {
next(error);
}
Expand All @@ -73,15 +72,18 @@ export const listaColetores = async (req, res, next) => {
export const atualizaColetor = async (req, res, next) => {
try {
const { id } = req.params;
const [updated] = await Coletor.update(req.body, {
where: { id },
});
if (updated) {
const updatedColetor = await Coletor.findByPk(id);
res.status(200).json(updatedColetor);
} else {

if (req.body.nome) req.body.nome = limparEspacos(req.body.nome);

const [updated] = await Coletor.update(req.body, { where: { id } });

if (!updated) {
throw new BadRequestException(404, 'Coletor não encontrado');
}

const updatedColetor = await Coletor.findByPk(id);

res.status(200).json(updatedColetor);
} catch (error) {
next(error);
}
Expand All @@ -92,26 +94,23 @@ export const desativaColetor = async (req, res, next) => {
const { id } = req.params;
const { Tombo } = models;

const coletor = await Coletor.findOne({
where: { id },
});
const coletor = await Coletor.findOne({ where: { id } });

if (!coletor) {
throw new BadRequestException(404, 'Coletor não encontrado');
}

const tombosAssociados = await Tombo.count({
where: {
coletor_id: id },
where: { coletor_id: id },
});

if (tombosAssociados > 0) {
throw new BadRequestException('Coletor não pode ser excluído porque possui dependentes.');
throw new BadRequestException(
'Coletor não pode ser excluído porque possui dependentes.',
);
}

await Coletor.destroy({
where: { id },
});
await Coletor.destroy({ where: { id } });

res.status(204).send();
} catch (error) {
Expand Down
14 changes: 9 additions & 5 deletions src/controllers/estados-controller.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import pick from '~/helpers/pick';

import BadRequestException from '../errors/bad-request-exception';
import limparEspacos from '../helpers/limpa-espaco';
import models from '../models';
import codigos from '../resources/codigos-http';

Expand All @@ -15,7 +16,9 @@ const {
const { Op } = Sequelize;

export const cadastrarEstado = (req, res, next) => {
const { nome, sigla, pais_id: paisId } = req.body;
let { nome, sigla, pais_id: paisId } = req.body;
nome = limparEspacos(nome);
sigla = limparEspacos(sigla);

const callback = async transaction => {
const estadoConflitante = await Estado.findOne({
Expand All @@ -40,7 +43,6 @@ export const cadastrarEstado = (req, res, next) => {
mensagem: `Já existe um estado com este ${campoDuplicado} neste país.`,
},
});

}

const estadoCriado = await Estado.create(
Expand Down Expand Up @@ -68,15 +70,15 @@ export const cadastrarEstado = (req, res, next) => {
export const listagem = async (req, res, next) => {
try {
const paisId = req.query.pais_id ? parseInt(req.query.pais_id, 10) : undefined;
const { nome } = req.query;
const nomeQuery = req.query.nome ? limparEspacos(req.query.nome) : undefined;

const where = {};
if (!Number.isNaN(paisId) && paisId !== undefined) {
where.pais_id = paisId;
}

if (nome) {
where.nome = { [Op.like]: `%${nome}%` };
if (nomeQuery) {
where.nome = { [Op.like]: `%${nomeQuery}%` };
}

const estados = await Estado.findAll({
Expand Down Expand Up @@ -112,6 +114,8 @@ export const atualizarEstado = async (req, res, next) => {
try {
const { estadoId } = req.params;
const dados = pick(req.body, ['nome', 'sigla', 'pais_id']);
if (dados.nome) dados.nome = limparEspacos(dados.nome);
if (dados.sigla) dados.sigla = limparEspacos(dados.sigla);

const estadoAtual = await Estado.findOne({ where: { id: estadoId } });
if (!estadoAtual) {
Expand Down
40 changes: 30 additions & 10 deletions src/controllers/herbarios-controller.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import BadRequestExeption from '../errors/bad-request-exception';
import NotFoundExeption from '../errors/not-found-exception';
import limparEspacos from '../helpers/limpa-espaco';
import omit from '../helpers/omit';
import models from '../models';
import codigos from '../resources/codigos-http';
Expand Down Expand Up @@ -114,10 +115,19 @@ export const cadastro = (request, response, next) => {
const callback = transaction => Promise.resolve()
.then(() => {
const { herbario } = request.body;
const where = {
email: herbario.email,
};

if (herbario.nome) herbario.nome = limparEspacos(herbario.nome);
if (herbario.sigla) herbario.sigla = limparEspacos(herbario.sigla);
if (herbario.email) herbario.email = limparEspacos(herbario.email);

const { endereco } = request.body;
Object.keys(endereco).forEach(campo => {
if (typeof endereco[campo] === 'string') {
endereco[campo] = limparEspacos(endereco[campo]);
}
});

const where = { email: herbario.email };
return Herbario.findOne({ where, transaction });
})
.then(herbario => {
Expand All @@ -137,9 +147,7 @@ export const cadastro = (request, response, next) => {
return Herbario.create(herbario, { transaction });
})
.then(herbario => {
const where = {
id: herbario.id,
};
const where = { id: herbario.id };

return Herbario.findOne({
transaction,
Expand All @@ -150,8 +158,7 @@ export const cadastro = (request, response, next) => {

sequelize.transaction(callback)
.then(herbario => {
response.status(201)
.json(herbario);
response.status(201).json(herbario);
})
.catch(ForeignKeyConstraintError, catchForeignKeyConstraintError)
.catch(next);
Expand All @@ -173,24 +180,38 @@ export const editar = (request, response, next) => {
}

const endereco = omit(request.body.endereco, ['id']);
Object.keys(endereco).forEach(campo => {
if (typeof endereco[campo] === 'string') {
endereco[campo] = limparEspacos(endereco[campo]);
}
});

const where = {
id: herbario.endereco_id,
};

if (herbario.endereco_id === null) {

const localizacao = await Endereco.create(endereco, { transaction });

const dados = {
...request.body.herbario,
endereco_id: localizacao.id,
};

if (dados.nome) dados.nome = limparEspacos(dados.nome);
if (dados.sigla) dados.sigla = limparEspacos(dados.sigla);
if (dados.email) dados.email = limparEspacos(dados.email);

return herbario.update(dados, { transaction });
}

const dados = omit(request.body.herbario, ['id', 'endereco_id']);

if (dados.nome) dados.nome = limparEspacos(dados.nome);
if (dados.sigla) dados.sigla = limparEspacos(dados.sigla);
if (dados.email) dados.email = limparEspacos(dados.email);

await Endereco.update(endereco, { where, transaction });

return herbario.update(dados, { transaction })
Expand All @@ -210,8 +231,7 @@ export const editar = (request, response, next) => {

sequelize.transaction(callback)
.then(herbario => {
response.status(200)
.json(herbario);
response.status(200).json(herbario);
})
.catch(ForeignKeyConstraintError, catchForeignKeyConstraintError)
.catch(next);
Expand Down
6 changes: 5 additions & 1 deletion src/controllers/identificador-controller.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import BadRequestException from '../errors/bad-request-exception';
import limparEspacos from '../helpers/limpa-espaco';
import models from '../models';
import codigos from '../resources/codigos-http';

const { Identificador, Sequelize: { Op } } = models;

export const cadastraIdentificador = async (req, res, next) => {
try {
if (req.body.nome) req.body.nome = limparEspacos(req.body.nome);
const identificador = await Identificador.create(req.body);
res.status(codigos.CADASTRO_RETORNO).json(identificador);
} catch (error) {
Expand Down Expand Up @@ -34,7 +36,8 @@ export const encontradaIdentificador = async (req, res, next) => {

export const listaIdentificadores = async (req, res, next) => {
try {
const { id, nome } = req.query;
let { id, nome } = req.query;
if (nome) nome = limparEspacos(nome);
const { limite, pagina } = req.paginacao;
const offset = (pagina - 1) * limite;

Expand Down Expand Up @@ -69,6 +72,7 @@ export const listaIdentificadores = async (req, res, next) => {

export const atualizaIdentificador = async (req, res, next) => {
try {
if (req.body.nome) req.body.nome = limparEspacos(req.body.nome);
const { id } = req.params;
const [updated] = await Identificador.update(req.body, {
where: { id },
Expand Down
Loading
Loading