2017-09-27 19 views
1

我實現了這個AWS Lambda,它接收來自鬆弛和響應的事件,然後回到鬆弛句子,我想監視它們的答案返回到lambda以驗證消息是否已到達併發布。AWS Lambda在請求後獲取https響應

// Lambda handler 
exports.handler = (data, context, callback) => { 
    switch (data.type) { 
     case "url_verification": verify(data, callback); break; 
     case "event_callback": process(data.event, callback); break; 
     default: callback(null); 
    } 
}; 

// Post message to Slack - https://api.slack.com/methods/chat.postMessage 
function process(event, callback) { 
    // test the message for a match and not a bot 
    if (!event.bot_id && /(aws|lambda)/ig.test(event.text)) { 
     var text = `<@${event.user}> isn't AWS Lambda awesome?`; 
     var message = { 
      token: ACCESS_TOKEN, 
      channel: event.channel, 
      text: text 
     }; 

     var query = qs.stringify(message); // prepare the querystring 
     https.get(`https://slack.com/api/chat.postMessage?${query}`); 
    } 

    callback(null); 
} 

我想知道我怎樣才能讓我的HTTPS請求(即由鬆弛發送給我)回到我的拉姆達的反應?

回答

1

如果我理解正確,你想等待你的查詢結果。

在你的代碼中,回調被立即調用,並且lambda完成它的執行。 爲了能夠等待響應,您需要從代碼中的當前位置刪除回調,並在執行請求後調用它。

// Post message to Slack - https://api.slack.com/methods/chat.postMessage 
function process(event, callback) { 
    // test the message for a match and not a bot 
    if (!event.bot_id && /(aws|lambda)/ig.test(event.text)) { 
     var text = `<@${event.user}> isn't AWS Lambda awesome?`; 
     var message = { 
      token: ACCESS_TOKEN, 
      channel: event.channel, 
      text: text 
     }; 

     var query = qs.stringify(message); // prepare the querystring 
     https.get(`https://slack.com/api/chat.postMessage?${query}`, (res, err) => { 
      if (err) return callback(err); 
      callback(null); 
     }) 
    } 

    // callback was here 
} 
1

如果可以,請使用request/request-promise來保存一些代碼行。

要在您的Lambda函數中獲得http響應,您只需在調用Lambda回調之前等待響應。

例如:

var request = require('request-promise'); 

exports.handler = (event, context, callback) => { 
    request('https://somedomain.com').then((body) => { 
    //got the response body 
    callback(null, body); 
    }); 
} 

這是同樣的想法,如果你使用的HTTPS模塊。

+0

謝謝,但我不能使用請求承諾。 – Nofar103