Skip to content
Snippets Groups Projects
rateSchool.js 2.78 KiB
Newer Older
Fernando Erd's avatar
Fernando Erd committed
const express = require('express');

const rateSchoolApp = express.Router();

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

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

const squel = require('squel');

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

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

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

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

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

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

const passport = require('passport');

const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;

rateSchoolApp.use(cache('15 day'));

let rqf = new ReqQueryFields();

// Complete range of the enrollments dataset.
// Returns a tuple of start and ending years of the complete enrollments dataset.
rateSchoolApp.get('/year_range', (req, res, next) => {
    req.sql.from('turma')
    .field('MIN(turma.ano_censo)', 'start_year')
    .field('MAX(turma.ano_censo)', 'end_year');
    next();
}, query, response('range'));

rateSchoolApp.get('/years', (req, res, next) => {
    req.sql.from('turma')
    .field('DISTINCT turma.ano_censo', 'year');
    next();
}, query, response('years'));

rateSchoolApp.get('/source', (req, res, next) => {
    req.sql.from('fonte')
    .field('fonte', 'source')
    .where('tabela = \'turma\'');
    next();
}, query, response('source'));

rateSchoolApp.get('/ethnic_group', (req, res, next) => {
    req.result = [];
    for(let i = 0; i <=5; ++i) {
        req.result.push({
            id: i,
            name: id2str.ethnicGroup(i)
        });
    }
    next();
}, response('ethnic_group'));


rqf.addField({
    name: 'filter',
    field: false,
    where: true
}).addField({
    name: 'dims',
    field: true,
    where: false
}).addValue({
    name: 'ethnic_group',
    table: 'pnad',
    tableField: 'cor_raca_id',
    resultField: 'ethnic_group_id',
    where: {
        relation: '=',
        type: 'integer',
        field: 'cor_raca_id'
    }
});

rateSchoolApp.get('/', rqfCount.parse(), rqfCount.build(), (req, res, next) => {
  log.debug(req.sql.toParam());
   req.sql.field('pnad')
   .field("'Brasil'", 'name')
   .field('pnad.ano_censo', 'year')
   .from('pnad')
   .group('pnad.ano_censo')
   .order('pnad.ano_censo')
   .where('pnad.faixa_etaria_31_03 = 0 OR pnad.faixa_etaria_31_03 = 1 OR pnad.faixa_etaria_31_03 = 2 OR pnad.faixa_etaria_31_03 = 3 OR pnad.faixa_etaria_31_03 = 4 OR pnad.faixa_etaria_31_03 = 5 OR pnad.faixa_etaria_31_03 = 6');
   next();
}, query, id2str.transform(), response('class'));

rateSchoolApp.get('/download', passport.authenticate('bearer', { session: false }), rqfCount.parse(), rqfCount.build(), download('turma', 'mapping_turma'));

module.exports = rateSchoolApp;