环回 - 在获取请求之前附加过滤器

loopback - append filter before get request

我正在为节点 JS 应用程序使用 Loopback。 Loopback 自动生成 CRUD api。所以,我试图改变一个 get api 所以也包括一个 table。我可以通过在查询中添加 include 过滤器来做到这一点

/api/expensecategories?filter[include]=vendors

但我想要 /api/expensecategories 到 return 和 table。为此,我之前使用 beforeRemote() 方法更改请求。

我的代码是:

expensecategories.beforeRemote('find', function (ctx, inst, next) {
   console.log(ctx.req.url);
   ctx.req.url = "/?filter[include]=vendors";
   console.log(ctx.req.url);
   console.log('GET api called');
   next();
});

这是更改请求 url 但不更改响应,它是相同的并且不包括 table。我尝试更改 req 中的所有内容,例如

ctx.req.query = {filter: { include: 'vendors' }};

但是没用。知道我怎样才能做到这一点。 table 的关系都已定义,我可以通过自定义 api 来获得所需的结果,例如

expensecategories.expensecategory = function (cb) {
    expensecategories.find({
      include: {
        relation : 'vendors',
      }
    }, function(err, data) {
    cb(null, data);
    });
  };

  expensecategories.remoteMethod (
    'expensecategory', {
       description: 'get all expense types + vendors',
       http: {path: '/yes', verb: 'get'},
       returns: {arg: 'expensecategory', type: 'string'}
    }
  );

所以,我的 table 关系和一切都是正确的。我也想要 /expensecategories 相同的结果。求助!!!

一种解决方案是覆盖 find 远程路径,如下所示:

expensecategories.remoteMethod (
 'expensecategory', {
   description: 'get all expense types + vendors',
   http: {
     path: '/', // <-- HERE
     verb: 'get'
   },
   returns: {arg: 'expensecategory', type: 'string'}
  }
);

Update :这在以前的 Loopback 版本中有效,在当前版本中你也必须这样做,在 expensecategories.setup() 调用之后:

expensecategories.disableRemoteMethod('find', true);

Update2:这就是您应该如何设置您的模型:

// This is automatically called by loopback
MyModel.setup = function() {
  // Super setup
  MyModel.base.setup.apply(this, arguments);

 // Your customization
  MyModel.remoteMethod(...);
  MyModel.disableRemoteMethod(...);
};

您可以通过添加 "scope" 部分将 ExpenseCategory 模型默认范围设置为包括供应商:

"scope": {
    "include": "vendor"
  }

我知道这个问题已经得到解答,但我从 Google 来到这里时遇到了类似的问题,因为我想在所有请求的查询中添加另一个过滤器参数。

有关系的东西对我不起作用,所以我继续挖掘并在文档中找到了这个 snippet on access hooks。所以最后我做了这个(基于你的例子):

expensecategories.observe('access', function (context, next) {
  context.query.where = context.query.where || {};
  context.query.where.include = 'vendors';
  next();
});