使用请求获取API结果,并集成到Hubot响应中

时间:2015-09-06 07:20:51

标签: javascript node.js coffeescript requestjs

我有一个Hubot插件,可以监听JIRA webhooks,并在创建新票证时在房间里宣布:

module.exports = (robot) ->
  robot.router.post '/hubot/tickets', (req, res) ->
    data = if req.body.payload? then JSON.parse req.body.payload else req.body
    if data.webhookEvent = 'jira:issue_created'
      console.dir("#{new Date()} New ticket created")
      shortened_summary = if data.issue.fields.summary.length >= 20 then data.issue.fields.summary.substring(0, 20) + ' ...' else data.issue.fields.summary
      shortened_description = if data.issue.fields.description.length >= 50 then data.issue.fields.description.substring(0, 50) + ' ...' else data.issue.fields.description
      console.log("New **#{data.issue.fields.priority.name.split ' ', 1}** created by #{data.user.name} (**#{data.issue.fields.customfield_10030.name}**) - #{shortened_summary} - #{shortened_description}")
      robot.messageRoom "glados-test", "New **#{data.issue.fields.priority.name.split ' ', 1}** | #{data.user.name} (**#{data.issue.fields.customfield_10030.name}**) | #{shortened_summary} | #{shortened_description}"
    res.send 'OK'

我想扩展它,对远程API执行查找 - 基本上,我想要查找额外的信息,然后添加到我传递给room.messageRoom的消息中。我正在使用请求,因为我需要摘要支持。

因此,以下代码段可以自行运行。

request = require('request')

company_lookup = request.get('https://example.com/clients/api/project?name=FOOBAR', (error, response, body) ->
  contracts = JSON.parse(body)['contracts']
  console.log contracts
).auth('johnsmith', 'johnspassword', false)

这就是我的JS / Node newbness出来的地方......哈哈。

我可以在回调中处理响应 - 但我真的确定如何在回调之外访问它?

我应该如何将其整合到webhook处理代码中?我只是将片段移动到if块中,并将其分配给变量吗?

1 个答案:

答案 0 :(得分:0)

我使用中间件(假设您正在使用带有Node.js的Express),因此您可以将company_lookup响应添加到req并将其用于添加中间件的任何路由。 http://expressjs.com/guide/using-middleware.html

例如:

server.js

var middlewares = require('./middlewares');
module.exports = function (robot) {
    // Tell the route to execute the middleware before continue
    return robot.router.post(middlewares.company_loop, '/hubot/tickets', function (req, res) {
        // Now in the req you have also the middleware response attached to req.contracts
        console.log(req.contracts);
        return res.send('OK');
    });
};

middlewares.js

var request = require('request');
// This is your middleware where you can attach your response to the req
exports.company_lookup = function (req, res, next) {
    request.get('https://example.com/clients/api/project?name=FOOBAR', function (error, response, body) {
        var contracts;
        contracts = JSON.parse(body)['contracts'];
        // Add the response to req
        req.contracts = contracts;
        // Tell it to continue
        next();
    }).auth('johnsmith', 'johnspassword', false);
};