Use more than one function in the Get Method route with Node.js

Asked

Viewed 229 times

-1

Good evening, I’m starting to learn about Ode and React.js and I’m having a problem because I need to use more than one function on the same route and by get method. I did the code below, it’s working, but I don’t know if it’s a right way to do it. I wonder if there’s another way less verbose. In this case, I used these two querys to show that I need to use more than one function per route in the Get method. The select won’t stay like this, it was just an example

module.exports = {
    async listar(request, response)  {
        const ano = request.body;
        const mes = request.body;

        const valor = {mensal:0,
                       anual:0};

        valor.mensal = await connection('entrada')
            .sum('valor_entrada')
            .whereRaw(`Year(data_entrada) = ${ano}`)



        valor.anual = await connection('entrada')
            .sum('valor_entrada')
            .whereRaw(`Month(data_entrada) = ${mes}`)

    return response.json(valor)


}
}

Here is my route

const express = require('express');
const connection = require('./database/connection');
const EntradaController = require('./controllers/EntradaController');

const routes = express.Router();

routes.get('/entradas', EntradaController.listar);

module.exports = routes;
  • You could do these operations in one SELECT only, plus your code is susceptible to SQL injection there whereRaw...

1 answer

0

Good friend , I’ll give you some tips , I hope it helps regarding the verbosity of the code, because it is a query in the same table but with different conditions, it may be that a raw with a SELECT direct work more think also that is not the best way out.

  module.exports = {
    async listar(request, response)  {
      const { ano, mes }  = request.body; // Desestruturação

        // Para as funções startOfYear e endOfYear use a lib date-fns
        const inicioAno = startOfYear(new Date(`${ano}-01-01`))
        const fimAno = endOfYear(new Date(`${ano}-01-01`))

        const mensal = await connection('entrada')
          .sum('valor_entrada')
          .whereBetween('data_entrada', [formattedStartYear, formattedEndYear])

        const anual = await connection('entrada')
          .sum('valor_entrada')
          .whereRaw(`Month(data_entrada) = ${mes}`) // Aqui voce está pegando todo os meses de todos os ano. Ex: 01/2020, 01/2019 .... Ai teria que procurar uma forma melhor por causa de um SQL Injection, se for do mesmo ano que vem no request ai é so fazer o que fiz acima para os meses

        const valor = {
          mensal,
          anual
        }

      return response.json(valor)
    }
  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.