Home > Back-end >  Pulling from aws aurora serverless database through lambda returns [Object Object]
Pulling from aws aurora serverless database through lambda returns [Object Object]

Time:03-02

My intention is to insert to the serverless mysql database through the lambda function, but at the very basic, I find that I am not even able to read from the database. Here is my code on the lambda -

const AWS = require('aws-sdk');
var rdsdataservice = new AWS.RDSDataService({apiVersion: '2018-08-01'});

var params = {
  secretArn: 'SERCRET_ARN',
  resourceArn: 'RESOURCE_ARN',
  //sql: 'INSERT INTO Users (UserId, GivenName) VALUES (\'USER-17788664349'\, \'theName'\)',
  sql: 'SELECT * from Users',
  database: 'DB',
};
exports.handler = async (event,context) => {
    var data;
    context.callbackWaitsForEmptyEventLoop =false;
        rdsdataservice.executeStatement(params, function(err, data) {
            if (err) {
                console.log(err, err.stack); // an error occurred 
            }
            else {
               data = data;    
            } 
        });
        console.log('RDS Data - ' data);
};

Running this soql returns RDS Data - [Object Object]. How do I access the records returned from aws aurora. Also really appreciate if someone could post an example of the insert statement with parameters.

CodePudding user response:

This is the way I was able to make it work -

exports.handler = async (event,context) => {
    context.callbackWaitsForEmptyEventLoop =false;        
    let result = await RDS.executeStatement(params).promise();
    console.log(JSON.stringify(result, null, 2))
    return 'done';
};

CodePudding user response:

I think the issue with the way async function AWS.RDSDataService.executeStatement is being executed. Try it with await and promise. For example:

exports.handler = async (event,context) => {
    var data;
    context.callbackWaitsForEmptyEventLoop =false;
        const result = await rdsdataservice.executeStatement(params, function(err, data) {
            if (err) {
                console.log(err, err.stack); // an error occurred 
            }
            else {
               data = data;    
            } 
        }).promise();
        console.log('RDS Data - ' data);
};

This way it worked for me. You probably see [Object Object] printed on console log because var data has not been assigned to anything actually. I also notice that some of the AWS documentation and the tutorials found elsewhere on the web are not very clear about this.

As for sample code for insert, it should work the same way.

  • Related