首页 > 解决方案 > 在 Loopback 3 中修改 ChangeStream 响应

问题描述

首先,如果您不熟悉变更流,请阅读内容。

似乎,当用于构建lb应用程序时,会自动为模型创建更改流端点。我已经成功实现了一个更改流,在向我的Statement模型提交新模型实例时,更改会实时发送到所有连接的客户端。这很好用。

除了它只发送模型modelInstance的。Statement我还需要了解提交声明的用户。由于与我的用户模型StatementhasOne关系,我通常会使用includes过滤器进行查询。但我不是在这里进行查询……这不是变更流的工作方式。节点服务器将信息发送到客户端,而不会首先发送对该信息的任何查询。

我的问题是,如何在 Statement 模型中挂钩传出的更改流,以便我可以从用户模块中提取所需的数据?就像是:

module.exports = function(Statement) {

  Statement.hookChangeStream(function(ctx, statementInstance, cb) {
    const myUser = Statement.app.models.myUser
    myUser.findOne({ 'where': { 'id': statementInstance.userId } }, function(err, userInstance) {
      if (err !== undefined && err !== null) cb(err, null);

      // strip sensitive data from user model
      cleanUserInstance = someCleanerFunc(userInstance);

      // add cleaned myUser modelInstance to Statement modelInstance
      statementInstance.user = cleanUserInstance;
      cb(null, true);
    }
  });

}

这可以做到吗?如果是这样,怎么做?

标签: loopbackjsserver-sent-eventschangestream

解决方案


推荐阅读