Giri
Giri

Reputation: 551

AWS Lambda function: returns null on querying postgresql

I am new to AWS. I am trying to connect to AWS RDS postgreSQL instance and query it using Lambda function. It returns null. Below is my code.

  var { Pool } = require('pg');
  exports.handler = function (event, context) {
  var dbConfig = {
    username: '<username>',
    password: '<password>',
    database: '<database>',
    host: '<db-endpoint>',
  };
  var pool = new Pool(dbConfig);
  exports.handler = async function (event, context, callback) {
    context.callbackWaitsForEmptyEventLoop = false;
    pool.connect();
    pool.query("select NOW() as now", (err, res)=>{
      console.log(res);
      if (err) return callback(err);
        if (res.rows.length==0){

            return callback(null, null);
        }
        else{
            return callback(null, res.rows[0]);
        }  
    });
 };

Upvotes: 2

Views: 635

Answers (1)

Robin Varghese
Robin Varghese

Reputation: 1189

Giri,

Your AWS Lambda needs proper permission to access AWS RDS (PostgreSQL). You have to create an Execution Role and get attached to the Lambda Service. https://docs.aws.amazon.com/lambda/latest/dg/services-rds-tutorial.html

Attached are a couple of images to show the results. enter image description here

enter image description here

Once you have successfully done this, You can jump into setting-up the Lambda package with code and driver to connect to AWS RDS PostGreSQL. Below 2 links will guide you through that. https://medium.com/@ly.lee/connecting-aws-lambda-node-js-to-redshift-or-postgresql-try-aws-lambda-layers-78e60c27f39b

https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-nodejs.rds.html

Upvotes: 2

Related Questions