MSP
MSP

Reputation: 45

How to return AWS Lambda callback values with node js

I am a bit new to AMS Lambda.

I wrote a small (working) function to execute a simple sql statement on HarperDB. The lambda function works well and the logs show the resulted rows from TableName

The question is how do I fetch or return the resultant values from the execution of SQL statement.

Following is my code

exports.handler = (event, context, callback) => {
  
  //console.log("Event is ",event);
  //console.log("Context is ",context);
  //console.log("callback is",callback)
  
    var https = require('follow-redirects').https;
    var fs = require('fs');
    
    console.log(context); // for analysis purpose
    
    var options = {
      'method': 'POST',
      'hostname': 'MyInstance-MyAccount.harperdbcloud.com',
      'path': '/',
      'headers': {
        'Authorization': 'Basic MyAuthoriztionCode',
        'Content-Type': 'application/json'
      },
      'maxRedirects': 20
    };
    
    var req = https.request(options, function (res) {
      var chunks = [];
    
      res.on("data", function (chunk) {
        chunks.push(chunk);
      });
    
      res.on("end", function (chunk) {
        var body = Buffer.concat(chunks);
        console.log(body.toString());
      });
    
      res.on("error", function (error) {
        console.error(error);
      });
    });
    
    var postData = JSON.stringify({
      "operation": "sql",
      "sql": "SELECT * FROM MyInstanceName.TableName"
    });
    
    req.write(postData, callback);
    req.end();
    
    const response = {
        statusCode: 200,
        body: JSON.stringify('Select Completed!'),
    };
    
    return (response);  // I want to get the result of execution of my sql statement
    
    };

How do I return the result of execution of the SQL statement

Upvotes: 1

Views: 375

Answers (1)

David
David

Reputation: 36

Add a call to the callback in the "end" event listener.

  res.on("end", function (chunk) {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
    callback(null, body.toString());
  });

Upvotes: 1

Related Questions