SeanPlusPlus
SeanPlusPlus

Reputation: 9033

Using the Node Request module with AWS Lambda and API Gateway

This lambda function works:

exports.handler = function(event, context, callback) {
  const done = (err, res, func) => callback(null, {
    statusCode: '200',
    body: res,
    headers: { 'Content-Type': 'application/json' },
  })

  done(null, 'works'))
}

I can hit the API Gateway end point and receive the response message, 'works'.

However, when I add a request call (POSTing a message to Slack) that looks like this:

const request = require('request')
const moment = require('moment-timezone')

exports.handler = function(event, context, callback) {
  // the json object is built following these docs:
  // https://api.slack.com/docs/message-attachments
  const SLACK_WEB_HOOK_URL = process.env.SLACK_WEB_HOOK_URL
  const uri = SLACK_WEB_HOOK_URL
  const method = 'POST'
  const options = {
    json,
    uri,
    method,
  }

  const slack = (opts) => {
    request.post(opts, (err, response, body) => {
      if (response.statusCode < 300) {
        return 'Success!'
      } else {
        return 'Err!'
      }
    })
  }

  const done = (err, res, func) => callback(null, {
    statusCode: '200',
    body: res,
    headers: { 'Content-Type': 'application/json' },
  })

  done(null, slack(options))
}

The server hangs when I hit the API end point ...

And I get a Task timed out after 10.00 seconds error:

{
  "errorMessage": "2017-06-23T16:41:21.483Z c385e32e-5832-11e7-8c4f-673b524cf783 Task timed out after 10.00 seconds"
}

But my Slack POST request gets sent and I see the message in the channel.

How do I send the POST request and then wait for it to return, and then exit the lambda function with a custom response message?

Thanks for the help!

Upvotes: 0

Views: 811

Answers (1)

MaiKaY
MaiKaY

Reputation: 4482

Put the callback into the callback of the post method

request.post(opts, (err, response, body) => {
    if (response.statusCode < 300) {
        return callback(null, {
            statusCode: '200',
            body: res,
            headers: { 'Content-Type': 'application/json' },
        });
    } else {
        return callback(err);
    }
});

Upvotes: 1

Related Questions