Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run SQL on PostgreSQL RDS from Lambda function in Node.js?

I have this code in Lambda funcion:

sql="SELECT ...";
var pg = require('pg');
var connectionString = 'postgres://...';

var client = new pg.Client(connectionString);
client.connect();
var query = client.query(sql);
query.on('end', function() { client.end(); });

When I run from EC2, it works fine. When I run from Lambda I get Error: Cannot find module 'pg'

like image 383
Eran Ben-Natan Avatar asked Aug 30 '15 10:08

Eran Ben-Natan


People also ask

Can you use RDS with Lambda?

Lambda can work seamlessly with RDS instances, as long as you remember the specific requirements for this particular setup. Since RDS instances are running in your VPC and Lambda by default does not have access to those resources, you'll need to configure the VPC connection when creating a Lambda function.


1 Answers

I am a super noob in Node JS, but I really wanted to try AWS Lambda. Here are the steps I took. I used a Ubuntu 14.04.

sudo apt-get update
sudo apt-get install nodejs
sudo apt-get install npm
sudo ln -s /usr/bin/nodejs /usr/bin/node

mkdir the_function && cd the_function
mkdir node_modules 
npm install pg

******Now create a file index.js and paste the content of your funcion.
console.log('Loading S2 Function');
var pg = require("pg");

exports.handler = function(event, context) {   
    var conn = "pg://user:password@host:5432/bd_name";

    var client = new pg.Client(conn);
    client.connect();

    var query = client.query("SELECT * FROM BLA WHERE ID = 1");
    query.on("row", function (row, result) {
        result.addRow(row);
    });
    query.on("end", function (result) {
        var jsonString = JSON.stringify(result.rows);
        var jsonObj = JSON.parse(jsonString);
        console.log(jsonString);
        client.end();
        context.succeed(jsonObj);
    });
 };

******Now zip the contents of the_function folder (not the_function folder itself)

You can check the official sample from this AWS link: http://docs.aws.amazon.com/lambda/latest/dg/walkthrough-s3-events-adminuser-create-test-function-create-function.html

like image 164
imTachu Avatar answered Oct 23 '22 06:10

imTachu