Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there Node.js examples for how to connect to AWS Aurora Serverless PostgreSQL via Lambda

I've set up an AWS Aurora Serverless PostgreSQL DB. I've also got API Gateway running endpoints to Lambda functions. Right now the Lambda functions are connecting to DynamoDB, but RDS is going to work better for my use case.

I've scoured the interwebs for hours but can't seem to find an example of how to access my Aurora Serverless DB via Lambda with Node.js. I'm not sure what imports I need in my function and I'm having a difficult time finding the right methods in the API as well.

Just a basic Node.js example to get me started would be amazingly helpful.

Thanks in advance.

like image 234
Aaron Austin Avatar asked Oct 10 '19 15:10

Aaron Austin


2 Answers

You should be able to connect to your Aurora instance with the same tools/client you are using to connect to your PostgreSQL database. For example when you navigate to your cluster's Connectivity and security tab you are shown an Endpoint name - you can use this and the port number in the connection string of any script.

Connecting to an Amazon Aurora PostgreSQL DB cluster Creating a DB cluster and connecting to a database on an Aurora PostgreSQL DB cluster

like image 97
juiceboxjoe Avatar answered Oct 22 '22 08:10

juiceboxjoe


I got a response on the AWS Developer Forums that was exactly what I needed to get started.

Evidently to use the PostgreSQL connector you have to build the function locally and import rather than use the online Lambda console.

Here is the example code provided by MrK: https://forums.aws.amazon.com/message.jspa?messageID=919394

//this imports the postgres connector into the file so it can be used
const { Client } = require('pg');

//instantiates a client to connect to the database, connection settings are passed in
const client = new Client({
    user: '<your db username>',
    host: '<your endpoint>',
    database: '<your database name>',
    password: '<your database password>',
    port: 5432
});

//the lambda funtion code
exports.handler = async (event, context, callback) => {

    try {

        await client.connect();
        callback(null, "Connected Successfully");
        //your code here

    } catch (err) {

        callback(null, "Failed to Connect Successfully");
        throw err;
        //error message
    }

    client.end();

};
like image 39
Aaron Austin Avatar answered Oct 22 '22 07:10

Aaron Austin