Query parameterized with Node.js and knex.js

Asked

Viewed 1,758 times

0

In the code below I make a query and bring the contracts that are concluded or not, according to the parameter concluido (0 or 1).

How do I bring this consultation all contracts when the parameter value is not passed concluido by requisition?

exports.read = function(req, res) {
    var concluido = parseInt(req.query.concluido);

    knex.select()
    .from('contrato as c')
    .innerJoin('empresa as e', 'e.idempresa', 'c.idempresa')
    .where('c.concluido', concluido)
    .then(function (result) {
        return res.status(200).json(result);
    })
    .catch(function (err) {
        return res.status(400).json(err);
    });
}

I currently have two knex functions that are called according to the conditions, but as I have several parameters I will have to create several functions, I believe that is not the correct way.

Note: it can be some example in SQL itself.

1 answer

2


One option is you split the string with a conditional:

let select = knex.select()
    .from('contrato as c')
    .innerJoin('empresa as e', 'e.idempresa', 'c.idempresa');

if (req.query.concluido) {
    select = select.where('c.concluido', concluido);
}

select
  .then(function (result) {
      return res.status(200).json(result);
  })
  .catch(function (err) {
      return res.status(400).json(err);
  });

So just put the WHERE if a conclusion comes, and another option is to use a trick in SQL:

let select = knex.select()
    .from('contrato as c')
    .innerJoin('empresa as e', 'e.idempresa', 'c.idempresa');
    .where('c.concluido', concluido)
    .orWhere(concluido, '');

select
  .then(function (result) {
      return res.status(200).json(result);
  })
  .catch(function (err) {
      return res.status(400).json(err);
  });

the . orWhere will act when the finished one comes empty.

Browser other questions tagged

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