将 webhook 订阅实施到 API 资源中

implementing webhook subscription into an API resource

考虑以下具有以下路由的原始 api 资源:

`POST` `{{baseurl}}/api/v1/users`    
//with request body of 
{
    "username":"adam12",
    "password":"abc123"
}

`GET` `{{baseurl}}/api/v1/users`   
`GET` `{{baseurl}}/api/v1/users/:id`   
`PUT` `{{baseurl}}/api/v1/users/:id`   
`DELETE` `{{baseurl}}/api/v1/users/:id`

其中 {{baseurl}}localhost:3000

我这里有有效实现的代码:https://github.com/mmcguff/webhookLearning

此时与此 users 资源交互的客户端必须发送 GET 请求才能了解此资源的更改。如果您需要来自此资源的实时数据,则必须创建一个轮询循环,该循环会消耗响应这些请求的服务器上的客户端资源。

我知道这个问题的正确解决方案是为此资源实施 webhook 订阅,但我在 node.js 中没有找到关于如何执行此操作的明确最佳实践类型信息。我在 npm 中找到的包目前下载量很少,这让我相信一定有其他人正在使用的更好的方法。

任何关于从 vanilla API 迁移到 webhook API 的帮助对我和社区中的每个人都非常有用。

对这种类型的事情使用队列是很常见的。 GitHub,例如,为 Ruby 开源的一个名为 resque a long while back. In Node specifically, you could look at bull。 Bull 使用 Redis 来存储类似于 resque 的排队事件。工作人员订阅他们关心的事件并相应地处理它们。

现在为您的用例提供一个实用但有限的示例:

const Queue = require('bull');
const rp = require('request-promise');

const userQueue = new Queue('user');

app.post(`/v1/users`, (req, res) => {
  userQueue.add({username: req.body.username, email: req.body.email});
  return res.send(`OK`);
});

const userSubscribers = [
  {
    hookUrl: `http://example.com/user-hook`
  }
];

userQueue.process(job => {
  return Promise.all(userSubscribers.map(subscriber => {
    const options = {
      method: `POST`,
      uri: subscriber.hookUrl,
      body: job.data,
      json: true
    };
    return rp(options);
  });
});

对于不同的权衡,您可以使用 Kafka 而不是 webhooks。