在 beforeRemote 远程挂钩内添加过滤器

2024-04-19

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

说我有一个模型Company和一个模型Employee。之间存在 1Xn 关系Company和它的Employees. When /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 对象。

我缺少什么?任何帮助将不胜感激!


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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 beforeRemote 远程挂钩内添加过滤器 的相关文章

随机推荐