Search code examples
node.jspostgresqldialogflow-es

How to query a Postgres DB in node.js (api.ai,node.js)


I have the following function in a node.js app:

if (parameters.hasOwnProperty("brand-param") && parameters["brand-param"] !='') {
    codes.readCodes(function(allCodes) {

the function readCodes is then called and within the function, I query the db:

readCodes: function(callback) {
      var pool = new pg.Pool(config.PG_CONFIG);
      pool.connect(function(err, client, done) {
          if (err) {
              return console.error('Error acquiring client', err.stack);
          }
          client
              .query(
                  `SELECT brand_code FROM public.voucher_codes WHERE brand_name=${parameters.hasOwnProperty("brand-param")} `,
                  function(err, result)

How do I query the db with the content of the “brand-param” for the WHERE part?


Solution

    1. The variable parameters defined inside apps.js must be passed to readCodes function in order to use it in the query.

    2. The check of brand_name is incorrect. It miss the use of single quotes and the parameter value itself is incorrect.


    if (parameters['brand-param'] && parameters['brand-param'].length) {
        codes.readCodes(parameters, function(allCodes) {
    

    readCodes: function(parameters, callback) {
      var pool = new pg.Pool(config.PG_CONFIG);
    
      pool.connect(function(err, client, done) {
          if (err) {
              return console.error('Error acquiring client', err.stack);
          }
    
     client.query(
       `SELECT brand_code FROM public.voucher_codes WHERE brand_name='${parameters['brand-param']}' `,
        function(err, result)