Can't return any value while connecting Redshift from Node JS
Asked Answered
A

1

0

The following code connected to Redshift database but returning an empty response even the response will be displayed in the console.log, why?

index.js

   
const config = {
  user: 'user',
  database: 'database',
  password: 'password',
  port: port,
  host: 'hostname',
};
var response = [];
console.log('Before Connection');
exports.handler =  function index(event, context, callback) {
  var redshiftClient = new Redshift(config, {rawConnection:true});
    redshiftClient.connect(function(err){
    console.log('After Connection');
    if(err) throw err;
    else{
      redshiftClient.query('SELECT * FROM customer', {raw: true}, function(err, data){
        if(err) throw err;
        else{
            response = data;
            console.log(data);
            redshiftClient.close();
            return response;
            
        }
         
      });
    }
  });
 
  return response;
};
Abdominous answered 22/6, 2021 at 8:39 Comment(0)
A
0

I have used the promise concept and it does returning the response properly for me. Sample JSON {"user_id": "1001"}

var Redshift = require('node-redshift');
   
const config = {
  user: 'user',
  database: 'database',
  password: 'password',
  port: port,
  host: 'hostname',
};

// The values passed in to the options object will be the difference between a connection pool and raw connection
var redshiftClient = new Redshift(config, {rawConnection:true});


exports.handler =  async (event) => {
return new Promise(function(resolve, reject){

redshiftClient.connect(function(err){
    if(err) throw err;
    else{
      redshiftClient.parameterizedQuery('SELECT * FROM customer where user_id = $1', [event.user_id], {raw: true}, function(err, data){
        if(err) throw reject(err);
        else{
          resolve(data);
          redshiftClient.close();
        }
      });
    }
  }); 
});

};
Abdominous answered 22/6, 2021 at 8:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.