1

我有一个 Hubot 插件,它监听 JIRA webhook,并在创建新票证时在房间内宣布:

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 新手出现的地方……哈哈。

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

我应该如何将它集成到 webhook 处理代码中 - 我是否只需将代码段移动到 if 块中,并将其分配给一个变量?

4

1 回答 1

0

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

例如:

服务器.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');
    });
};

中间件.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);
};
于 2015-09-06T08:00:33.050 回答