1
votes

I'm trying to post data from a the OData RESTful API from a sample service used which is the TripPin. The request succeeded but the response est null. Is there any particular structure to respect in AWS Lambda platform in order to make HTTP post request?

var querystring = require('querystring');
var http = require('http');

exports.handler = function (event, context) {
var post_data = querystring.stringify(
     {
    UserName:'lewisblack',
    FirstName:'Lewis',
    LastName:'Black',
    Emails:[
        '[email protected]'
    ],
    AddressInfo:[
        {
            Address: '187 Suffolk Ln.',
            City: {
CountryRegion: 'United States',
Name: 'Boise',
Region: 'ID'
            }
        }
    ],
    Gender: 'Male'
}
  );


  // An object of options to indicate where to post to
  var post_options = {
      host: event.url,
      port: '80',
      path: event.path,
      method: 'POST',
      headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': Buffer.byteLength(post_data)
      }
  };

  // Set up the request
  var post_req = http.request(post_options, function(res) {
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
          console.log('Response: ' + chunk);
          console.log("hello");
          context.succeed();
      });
      res.on('error', function (e) {
        console.log("Got error: " + e.message);
        context.done(null, 'FAILURE');
      });

  });

  // post the data
  post_req.write(post_data);
  post_req.end();

}

Example of Call Parameters :

{
  "url": "services.odata.org",
  "path": "/v4/TripPinServiceRW/"
}

Response: null

Request ID: "6f1ec2b4-5195-477f-9fb8-56fd33dee0ce"

Function Logs: START RequestId: 6f1ec2b4-5195-477f-9fb8-56fd33dee0ce Version: $LATEST

END RequestId: 6f1ec2b4-5195-477fenter code here-9fb8-56fd33dee0ce

REPORT RequestId: 6f1ec2b4-5195-477f-9fb8-56fd33dee0ce Duration: 431.87 ms

Billed Duration: 500 ms Memory Size: 128 MB Max Memory Used: 73 MB

1

1 Answers

3
votes

TL;DR; I think your AWS Lambda integration is broken, but it's hard for me to know for sure. Apologies for the lecture.

I recommend the following:

Figure out what you're getting in the event

What you get in the event object depends on how you are calling your AWS Lambda function. You can invoke it directly via an API call, or indirectly by having another AWS service trigger it. Note that:

The structure of the event document is different for each event type, and contains data about the resource or request that triggered the function

https://docs.aws.amazon.com/lambda/latest/dg/lambda-services.html

The easiest way to find out would probably be to add some logging at the start of your handler:

console.log(JSON.stringify(event));

Write Some Tests!

Once you've figured out what's actually in the event object, write a test for it. This should improve both the design of your code and your development cycle.

Testing the code above against a local test server gives a successful response. See below.

But that doesn't mean it will work against https://services.odata.org.

  • That api looks like it's read only, but you're trying to write to it.
  • You're calling it over HTTP on port 80. It looks like it wants to be called by HTTPS on port 443.

Again, you should figure out how you should call that service and write a test for it.

Example Test Case

index.spec.js

var index = require("./index");

describe('index', () => {
    it('can make requests to localhost', (done) => {
        return index.handler({
            "url": "localhost",
            "path": "/"
          }, {
              done: done,
              succeed: done
        });
    });
});

package.json

  ...
  "scripts": {
    "test": "jest"
  },
  "devDependencies": {
    "jest": "^24.8.0"
  }
  ...

Output:

> npm test

  > [email protected] test /somepath/index.spec.js
  > jest

   PASS  ./index.spec.js
    index
      ✓ can make requests to localhost (20ms)

    console.log index.js:44
      Response: <html><body><h1>POST!</h1></body></html>

    console.log index.js:45
      hello

  Test Suites: 1 passed, 1 total
  Tests:       1 passed, 1 total
  Snapshots:   0 total
  Time:        0.89s, estimated 1s
  Ran all test suites.

Use a simpler http library

You're using a low level node http library. A library like axios may make your life easier in the short term. See the HTTP Post example on their readme / wiki.