Aravind Reddy
Aravind Reddy

Reputation: 363

Unable to return result when using AWS Lambda NodeJS

I am trying to implement a simple Node Js function on AWS Lambda to query data from dynamoDB. I hooked this lambda function to my API gateway, but I don't see any results when i access the API url.

//Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'us-east-1'});

// Create DynamoDB service object
var b = new AWS.DynamoDB({apiVersion: '2012-08-10'});

var params = {
   ExpressionAttributeNames: {
    "#devicetimestamp": "timestamp"
  },
  ExpressionAttributeValues: {
    ':unitID': {S: 'arena-MXHGMYzBBP5F6jztnLUdCL'},
    ':dtimestamp' : {S: '1582920096000'}
   },
 KeyConditionExpression: 'id = :unitID and #devicetimestamp > :dtimestamp',
 TableName: 'IoTdata2'
};

b.query(params, function(err, results) {
    if (err) {
        console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
    } else {
        console.log("Query succeeded.");
        console.log(JSON.stringify(results));
    }
});

Code works fine as i see the results from console.log(JSON.stringify(results)); when i use event handler

//Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'us-east-1'});

// Create DynamoDB service object
var b = new AWS.DynamoDB({apiVersion: '2012-08-10'});

exports.handler =  (event, context, callback) => {

var params = {
   ExpressionAttributeNames: {
    "#devicetimestamp": "timestamp"
  },
  ExpressionAttributeValues: {
    ':unitID': {S: 'arena-MXHGMYzBBP5F6jztnLUdCL'},
    ':dtimestamp' : {S: '1582920096000'}
   },
 KeyConditionExpression: 'id = :unitID and #devicetimestamp > :dtimestamp',
 TableName: 'IoTdata2'
};

b.query(params, function(err, results) {
    if (err) {
        console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
        callback(err);
    } else {
        console.log("Query succeeded.");
        console.log(JSON.stringify(results));
       callback(null, results);
    }
});
};

```i don't see any response in API URL.I am new to nodeJS, Any suggestions will be greatly appreciated. Thanks

Upvotes: 0

Views: 378

Answers (1)

bryan60
bryan60

Reputation: 29305

since you're going through API gateway, there's a specific response contract from lambda you need to meet, try doing it like this:

const response = {
  statusCode: 200, // need a status code
  body: JSON.stringify(results) // and a string body
}

callback(null, response)

a bit more info here: TUTORIAL: Build a Hello World API with Lambda Proxy Integration - Amazon API Gateway

Upvotes: 3

Related Questions