diff --git a/src/controllers/coletor-controller.js b/src/controllers/coletor-controller.js index 07a0b6e..877e0ee 100644 --- a/src/controllers/coletor-controller.js +++ b/src/controllers/coletor-controller.js @@ -2,15 +2,26 @@ import BadRequestException from '../errors/bad-request-exception'; import models from '../models'; import codigos from '../resources/codigos-http'; -const { Coletor } = models; +const { Coletor, Sequelize: { Op } } = models; export const cadastraColetor = async (req, res, next) => { try { + if (req.body.numero) { + const validaNumero = await Coletor.findOne({ + where: { numero: req.body.numero }, + }); + + if (validaNumero) return res.status(400).json({ mensagem: 'Número do coletor já está em uso.' }); + } + 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) => { @@ -34,11 +45,19 @@ export const encontraColetor = async (req, res, next) => { export const listaColetores = async (req, res, next) => { try { + const { id, nome } = req.query; const { limite, pagina } = req.paginacao; const offset = (pagina - 1) * limite; + const where = { ativo: true }; + if (id) { + where.id = id; + } else if (nome) { + where.nome = { [Op.like]: `%${nome}%` }; + } + const result = await Coletor.findAndCountAll({ - where: { ativo: true }, + where, order: [['id', 'ASC']], limit: limite, offset, diff --git a/src/controllers/identificador-controller.js b/src/controllers/identificador-controller.js index 93f7c7f..596162c 100644 --- a/src/controllers/identificador-controller.js +++ b/src/controllers/identificador-controller.js @@ -14,9 +14,8 @@ export const cadastraIdentificador = async (req, res, next) => { }; export const encontradaIdentificador = async (req, res, next) => { - const { id } = req.params; - try { + const { id } = req.params; const identificador = await Identificador.findOne({ where: { id }, }); @@ -48,7 +47,7 @@ export const listaIdentificadores = async (req, res, next) => { const result = await Identificador.findAndCountAll({ where, - attributes: ['id', 'nome'], + order: [['id', 'ASC']], limit: limite, offset, }); diff --git a/src/validators/coletor-cadastro.js b/src/validators/coletor-cadastro.js index b0fcad3..d7dcf6b 100644 --- a/src/validators/coletor-cadastro.js +++ b/src/validators/coletor-cadastro.js @@ -18,6 +18,6 @@ export default { numero: { in: 'body', isInt: true, - isEmpty: false, + optional: true, }, };