在hubot coffeescript中同时调用2个https请求

时间:2014-03-06 06:21:06

标签: coffeescript hubot

module.exports = (robot) ->
  robot.respond /log (.*)/i, (msg) ->
    group = "test"
    incident_message = msg.match[0]
    service_key = keys[group]
    curtime = new Date().getTime()
    incident_key = "hubot/#{curtime}"
    reporter = msg.message.user.name
    query = {
      "service_key": service_key,
      "incident_key": incident_key,
      "event_type": "trigger",
      "description": "Change Log #{reporter}",
      "details": "#{incident_message}"
    }
    string_query = JSON.stringify(query)
    content_length = string_query.length
    msg
      .http("https://events.pagerduty.com/generic/2010-04-15/create_event.json")
      .headers
      "Content-type": "application/json",
      "Content-length": content_length
      .post(string_query) (err, res, body) ->
      result = JSON.parse(body)
      if result.status == "success"
        msg.send "Your log has been sent"
      else
        msg.send "There was an error sending your log."
    msg
      .http("https://xyz.pagerduty.com/api/v1/incidents/#{incident_key}/acknowledge")

我正在尝试自动确认在pagerduty中触发的事件。第一个http请求生效。但第二个http请求(代码的最后一行)永远不会生效。我尝试了varipus组合。但它没有帮助。我是coffeescript的新手,只能用于hubot。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

首先,您没有指定您正在执行的HTTP操作:

msg.http("https://xyz.pagerduty.com/api/v1/incidents/#{incident_key}/acknowledge")

应以.get().post()结束。

另外,可能是由于粘贴不好,你的缩进如果在中间偏离了一点:

  .post(string_query) (err, res, body) ->
  result = JSON.parse(body)
  if result.status == "success"
    msg.send "Your log has been sent"
  else
    msg.send "There was an error sending your log."

应该是:

  .post(string_query) (err, res, body) ->
    result = JSON.parse(body)
    if result.status == "success"
      msg.send "Your log has been sent"
    else
      msg.send "There was an error sending your log."

另一件事,由于NodeJS的性质,这些HTTP调用是异步进行的,并且第二次调用很可能在第一次调用之前完成。为避免这种情况,请从第一个请求的回调中运行第二个请求:

msg
  .http("https://events.pagerduty.com/generic/2010-04-15/create_event.json")
  .headers
  "Content-type": "application/json",
  "Content-length": content_length
  .post(string_query) (err, res, body) ->
    result = JSON.parse(body)
    if result.status == "success"
      msg.send "Your log has been sent"
      msg
        .http("https://xyz.pagerduty.com/api/v1/incidents/#{incident_key}/acknowledge")
        .get()
    else
      msg.send "There was an error sending your log."

您可以找到一些Hubot HTTP请求和其他脚本技巧here的示例。