Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/get points cities #48

Merged
merged 9 commits into from
Aug 29, 2024
Merged
File renamed without changes.
126 changes: 117 additions & 9 deletions src/controllers/cidades-controller.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import models from '../models';

const {
Cidade,
} = models;
const { Op } = require('sequelize');

export const listaTodosCidades = where => Cidade.findAndCountAll({
attributes: {
exclude: ['updated_at', 'created_at'],
},
where,
});
const { Cidade, LocalColeta, Tombo } = models;

export const listaTodosCidades = where =>
Cidade.findAndCountAll({
attributes: {
exclude: ['updated_at', 'created_at'],
},
where,
});

export const listagem = (request, response, next) => {
let where = {};
Expand All @@ -26,3 +27,110 @@ export const listagem = (request, response, next) => {
})
.catch(next);
};

export const ListaTodosOsTombosComLocalizacao = async (req, res, next) => {
try {
const { cidade, search } = req.query;
const { limite: limit, pagina: pageInt, offset } = req.paginacao;

if (!cidade && !search) {
const tombos = await Tombo.findAll({
attributes: ['hcf', 'latitude', 'longitude'],
include: {
model: LocalColeta,
include: {
model: Cidade,
attributes: ['nome', 'latitude', 'longitude'],
},
},
order: [['hcf', 'ASC']],
});

const result = tombos.map(tombo => {
const localColeta = tombo.locais_coletum;
const cidadeObj = localColeta ? localColeta.cidade : null;

return {
hcf: tombo.hcf,
latitude: tombo.latitude,
longitude: tombo.longitude,
cidade: {
nome: cidadeObj ? cidadeObj.nome : null,
latitude: cidadeObj ? cidadeObj.latitude : null,
longitude: cidadeObj ? cidadeObj.longitude : null,
},
};
});

return res.status(200).json(result);
}

const queryOptions = {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Acho que conseguimos melhorar esta lógica aqui para não repetir tanto o código. Você pode ir adicionando os novos parâmetros na query caso eles existam ou não. Você pode verificar na listagem de tombos como isso é feito. Se ficar com alguma dúvida me avisa e conversamos por chamada.

attributes: ['hcf', 'latitude', 'longitude'],
where: {
latitude: null,
longitude: null,
},
include: {
model: LocalColeta,
required: true,
include: {
model: Cidade,
required: true,
attributes: ['nome', 'latitude', 'longitude'],
where: {},
},
},
order: [['hcf', 'ASC']],
};

if (req.query.pagina && req.query.limite) {
queryOptions.limit = limit;
queryOptions.offset = offset;
}

if (cidade) {
queryOptions.include.include.where.nome = cidade;
}

if (search) {
queryOptions.where.hcf = {
[Op.like]: `%${search}%`,
};
}

const tombos = await Tombo.findAndCountAll(queryOptions);

const result = tombos.rows.map(tombo => {
const localColeta = tombo.locais_coletum;
const cidadeObj = localColeta ? localColeta.cidade : null;

return {
hcf: tombo.hcf,
latitude: tombo.latitude,
longitude: tombo.longitude,
cidade: {
nome: cidadeObj ? cidadeObj.nome : null,
latitude: cidadeObj ? cidadeObj.latitude : null,
longitude: cidadeObj ? cidadeObj.longitude : null,
},
};
});

const response = {
points: result,
totalPoints: tombos.count,
};

if (req.query.pagina && req.query.limite) {
response.totalPages = Math.ceil(tombos.count / limit);
response.currentPage = pageInt;
}

return res.status(200).json(response);
} catch (error) {
next(error);
}

return res.status(500).json({ message: 'Internal server error' });
};
35 changes: 17 additions & 18 deletions src/middlewares/tokens-middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,26 @@
IDENTIFICADOR: 3,
};

export default (tipoUsuarioPermitido = []) => (request, response, next) => {
export default (tipoUsuarioPermitido = []) =>
(request, response, next) => {
const token = request.headers['token']; // eslint-disable-line

try {
if (typeof token !== 'string') {
throw new ForbiddenException(101);
}
try {
if (typeof token !== 'string') {
throw new ForbiddenException(101);
}

const usuario = decodificaTokenUsuario(token);
const usuario = decodificaTokenUsuario(token);

const estaPermitido = !Array.isArray(tipoUsuarioPermitido)
|| tipoUsuarioPermitido.length < 1
|| tipoUsuarioPermitido.includes(usuario.tipo_usuario_id);
const estaPermitido = !Array.isArray(tipoUsuarioPermitido) || tipoUsuarioPermitido.length < 1 || tipoUsuarioPermitido.includes(usuario.tipo_usuario_id);

Check warning on line 23 in src/middlewares/tokens-middleware.js

View workflow job for this annotation

GitHub Actions / lint

This line has a length of 164. Maximum allowed is 150

if (!estaPermitido) {
throw new ForbiddenException(102);
}
if (!estaPermitido) {
throw new ForbiddenException(102);
}

request.usuario = usuario;
next();
} catch (err) {
next(err);
}
};
request.usuario = usuario;
next();
} catch (err) {
next(err);
}
};
8 changes: 8 additions & 0 deletions src/models/Cidade.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,14 @@ export default (Sequelize, DataTypes) => {
type: DataTypes.INTEGER,
allowNull: true,
},
latitude: {
type: DataTypes.DOUBLE,
allowNull: true,
},
longitude: {
type: DataTypes.DOUBLE,
allowNull: true,
},
};

const options = {
Expand Down
6 changes: 1 addition & 5 deletions src/routes/cidades.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
const controller = require('../controllers/cidades-controller');

export default app => {

app.route('/cidades')
.get([
controller.listagem,
]);
app.route('/cidades').get(controller.listagem);
};
2 changes: 2 additions & 0 deletions src/routes/tombos.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ListaTodosOsTombosComLocalizacao } from '../controllers/cidades-controller';
import fichaTomboController from '../controllers/fichas-tombos-controller';
import {
getDadosCadTombo, getNumeroTombo, cadastro, listagem,
Expand Down Expand Up @@ -143,4 +144,5 @@ export default app => {

// app.route('/fichas/tombos/:tombo_id')
// .get(fichaTomboController);
app.route('/pontos').get([listagensMiddleware, ListaTodosOsTombosComLocalizacao]);
};
Loading
Loading