Jitender
Jitender

Reputation: 7971

make postgres condition query in nodejs

I have select query and I want to add filter and search values to select query. The user can perform a search and filter separately and together as well. Following are the scenario:

when I applied only search (Success)

select name, id from master.contact where name ilike 'sal%' or name ilike 'man%';

when I applied only first filter (Success)

select name, id from master.contact where isActive=true;

when I applied both filters (Success)

select name, id from master.contact where isActive=true and pan='abcd';

when I applied only the second filter (Fail)

select name, id from master.contact and pan='abcd';

when I applied search and both filters (Fail)

select * from master.contact where name ilike 'sal%' or name ilike 'man%' where master.contact.is_active = true and pan='abcd';

when I applied search and first filter (Fail)

select * from master.contact where name ilike 'sal%' or name ilike 'man%' where master.contact.is_active = true;

nodejs

const query = {
    text: `
      select master.contact.id,
      master.contact.name
      from
      master.contact
       `
  };
  if (input.search) {
    query.text += ` where
    (master.contact.pan ILIKE '${input.search}%' or master.contact.ira ILIKE '${input.search}%')`;
  }

  if (input.filters) {
    const {
      isActive,
      pan
    } = input.filters;
    if (isActive !== undefined) {
      query.text += ` where master.contact.isActive = ${isActive}`;
    }

    if (pan) {
      query.text += `and master.contact.pan = ${pan}`;
    }

Upvotes: 1

Views: 1171

Answers (1)

Nick
Nick

Reputation: 7431

How about collect the criteria in an array then join and append it, like so:

const query = {
    text: `
      select master.contact.id,
      master.contact.name
      from
      master.contact
       `
  };

// Create an array to store any criteria
var where = [];

  if (input.search) {
    where.push(`(master.contact.pan ILIKE '${input.search}%' or master.contact.ira ILIKE '${input.search}%')`);
  }

  if (input.filters) {
    const {
      isActive,
      pan
    } = input.filters;
    if (isActive !== undefined) {
      where.push(`master.contact.isActive = ${isActive}`);
    }

    if (pan) {
      where.push(`master.contact.pan = ${pan}`);
    }

// If criteria were added, append to query text
if (where.length > 0) {
   query.text += ' where ' + where.join(' and ');
}

Upvotes: 2

Related Questions