Search code examples
coffeescripthubot

Returning result from nested anonymous function in a hubot script


Having never worked with coffescript before, I'm trying to update the hubot script for jenkins integration. In a nutshell I want to call jenkins, get a result from that call and use it in a subsequent call. Based on the existing code in the hubot script I've added the following function:

jenkinsCrumb = (msg) ->
    url = process.env.HUBOT_JENKINS_URL
    path = "#{url}/crumbIssuer/api/json"

    req = msg.http(path)

    if process.env.HUBOT_JENKINS_AUTH
      auth = new Buffer(process.env.HUBOT_JENKINS_AUTH).toString('base64')
      req.headers Authorization: "Basic #{auth}"

    req.get() (err, res, body) ->
        if err
          msg.reply "Jenkins says: #{err}"
        else if 200 <= res.statusCode < 400 # Or, not an error code.
          msg.reply "#{body}"
          body
        else if 404 == res.statusCode
          msg.reply "Unable to fetch crumb from Jenkins..."
        else
          msg.reply "Jenkins says: Status #{res.statusCode} #{body}"

When this function is called, the value I want is reported in the variable body. The call to msg.reply properly displays the value in the hubot chat window.

What I would like to do, but can't figure out, is how to have this function return the value of body? I've tried explicitly returning the value of req.get() but it seems that it's returning the full request object.


Solution

  • You can do that by simply adding return body or just body (because of CoffeeScript) to the end of your anonymous function:

    jenkinsCrumb = (msg, callback) ->
        url = process.env.HUBOT_JENKINS_URL
        path = "#{url}/crumbIssuer/api/json"
    
        req = msg.http(path)
    
        if process.env.HUBOT_JENKINS_AUTH
          auth = new Buffer(process.env.HUBOT_JENKINS_AUTH).toString('base64')
          req.headers Authorization: "Basic #{auth}"
    
        req.get() (err, res, body) ->
            if err
              msg.reply "Jenkins says: #{err}"
            else if 200 <= res.statusCode < 400 # Or, not an error code.
              msg.reply "#{body}"
              body
            else if 404 == res.statusCode
              msg.reply "Unable to fetch crumb from Jenkins..."
            else
              msg.reply "Jenkins says: Status #{res.statusCode} #{body}"
    
            # critical part
            callback(body)