Skip to content
Snippets Groups Projects
population.js 2.64 KiB
const express = require('express');

const populationApp = express.Router();

const libs = `${process.cwd()}/libs`;

const log = require(`${libs}/log`)(module);

const squel = require('squel');

const query = require(`${libs}/middlewares/query`);

const response = require(`${libs}/middlewares/response`);

const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`);

const id2str = require(`${libs}/middlewares/id2str`);

let rqf = new ReqQueryFields();

populationApp.get('/year_range', (req, res, next) => {
    req.sql.from('ibge_populacao')
    .field('MIN(ibge_populacao.ano_censo)', 'start_year')
    .field('MAX(ibge_populacao.ano_censo)', 'end_year');
    next();
}, query, response('range'));

rqf.addField({
    name: 'filter',
    field: false,
    where: true
}).addField({
    name: 'dims',
    field: true,
    where: false
}).addValue({
    name: 'city',
    table: 'municipio',
    tableField: 'nome',
    resultField: 'city_name',
    where: {
        relation: '=',
        type: 'integer',
        field: 'municipio_id',
        table: 'ibge_populacao'
    },
    join: {
        primary: 'id',
        foreign: 'municipio_id',
        foreignTable: 'ibge_populacao'
    }
}).addValue({
    name: 'state',
    table: 'estado',
    tableField: 'nome',
    resultField: 'state_name',
    where: {
        relation: '=',
        type: 'integer',
        field: 'estado_id',
        table: 'ibge_populacao'
    },
    join: {
        primary: 'id',
        foreign: 'estado_id',
        foreignTable: 'ibge_populacao'
    }
}).addValue({
    name: 'min_year',
    table: 'ibge_populacao',
    tableField: 'ano_censo',
    resultField: 'year',
    where: {
        relation: '>=',
        type: 'integer',
        field: 'ano_censo'
    }
}).addValue({
    name: 'max_year',
    table: 'ibge_populacao',
    tableField: 'ano_censo',
    resultField: 'year',
    where: {
        relation: '<=',
        type: 'integer',
        field: 'ano_censo'
    }
});

populationApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
  log.debug(req.sql.toParam());
   req.sql.field('ibge_populacao.populacao', 'population')
   .field('ibge_populacao.municipio_id', 'municipio_id')
   .field('ibge_populacao.ano_censo', 'year')
   .from('ibge_populacao')
   .group('ibge_populacao.populacao')
   .group('ibge_populacao.municipio_id')
   .group('ibge_populacao.ano_censo')
   next();
}, query, (req, res, next) => {
    // let somapop = 0;
    // for (var i = 0; i < req.result.length; i++) {
    //     somapop += req.result[i].population;
    // }
    //
    // req.result = [somapop];
    next()
}, id2str.transform(true), response('population'));

module.exports = populationApp;