在beforeRemote远程钩子中添加过滤器 [英] Adding a filter inside a beforeRemote remote hook

查看:73
本文介绍了在beforeRemote远程钩子中添加过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a problem I can't find an answer to in Loopback's docs.

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

Say I have a model Company and a modelEmployee. There is an 1Xn relation between the Company and its Employees. When /api/Employees is called, server returns all the employees.

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

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

For this, I created a remote hook

     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();
        });

    });

我认为这应该每次都有用,但看起来它只适用于已经有一些查询过滤器之类的include - 尽管console.log打印了一个正确的context.req.query对象。

I thought this should work every time, but appearantly it only works when find already has some query filters like include - although the console.log prints a correct context.req.query object.

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

推荐答案

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

context.args.filter seems to work for this purpose. As a side note, instead of replacing where, you might want to merge it with something provided by client. For implementation idea you can refer to: https://github.com/strongloop/loopback-datasource-juggler/blob/master/lib/utils.js#L56-L122

这篇关于在beforeRemote远程钩子中添加过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆