【问题标题】:Adding a filter inside a beforeRemote remote hook在 beforeRemote 远程挂钩中添加过滤器
【发布时间】:2015-04-01 07:40:04
【问题描述】:

我有一个问题,我在 Loopback 的文档中找不到答案。

假设我有一个模型Company 和一个模型EmployeeCompany 与其Employees 之间存在 1Xn 关系。当调用/api/Employees 时,服务器返回所有员工。

我只想返回与请求列表的用户在同一公司的员工列表。

为此,我创建了一个远程挂钩

     Employee.beforeRemote('find', function(context, modelInstance, next) {
        var reject = function() {
            process.nextTick(function() {
                next(null, false);
            });
        };

        // do not allow anonymous users
        var userId = context.req.accessToken.userId;
        if (!userId) {
            return reject();
        }

        //I get the details of the user who sent the request 
        //to learn which company does he belong to
        Employee.findById(userId, function(err, user) {
            if(!context.req.query.filter) context.req.query.filter={};
            context.req.query.filter.where = {brandId:user.companyId};
            console.log(context.req.query);
            next();
        });

    });

我认为这应该每次都有效,但看起来它仅在 find 已经有一些查询过滤器(如 include)时才有效 - 尽管 console.log 打印了正确的 context.req.query 对象。

我错过了什么?任何帮助将不胜感激!

【问题讨论】:

  • 你是说beforeRemote()钩子函数在没有过滤器传递给find()时没有被调用,或者你的代码在没有提供过滤器的情况下特别不起作用?
  • 问题是 context.req.query.filter 在没有从客户端请求中设置时被忽略。不过 Alex 的建议奏效了,谢谢大家的帮助。

标签: javascript loopbackjs strongloop


【解决方案1】:

context.args.filter 似乎可以用于此目的。 作为旁注,您可能希望将其与客户端提供的内容合并,而不是替换 where。实现思路可以参考:https://github.com/strongloop/loopback-datasource-juggler/blob/master/lib/utils.js#L56-L122

【讨论】:

  • 我想做同样的事情,但是我得到一个“TypeError:无法分配给只读属性......”。您在处理此问题时是否见过这种情况?
猜你喜欢
  • 2015-04-06
  • 1970-01-01
  • 2019-12-02
  • 2017-03-28
  • 2019-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多