在beforeRemote远程钩子中添加过滤器

Mih*_* KR 7 javascript strongloop loopbackjs

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

说我有模特Company和模特Employee.它Company和它之间有1Xn的关系Employees.当/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();
        });

    });
Run Code Online (Sandbox Code Playgroud)

我认为这应该每次都有用,但是看起来它只有当find已经有一些像include这样的查询过滤器时才会起作用 - 尽管console.log会输出正确的context.req.query对象.

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

Ale*_*x V 11

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