如何在FeathersJS中构造条件钩子?

时间:2017-03-07 03:49:22

标签: feathersjs

我一直在阅读文档,但我似乎无法做到正确。

我正在尝试通过包装一些提供的钩子来实现自定义条件钩子。它应该通过以下方式限制对服务的访问(方法无关紧要):

1)首先使用以下方式检查用户是否具有adminsuper-admin角色:

auth.restrictToRoles({
  roles: ['admin', 'super-admin']
}),

如果用户具有所需角色,则挂钩应允许访问。否则..

2)使用以下方法限制对所有者的访问:

auth.restrictToOwner({ ownerField: 'id' }), 

我无法弄清楚如何获取并检查auth.restrictToRoles的结果,以便我可以根据需要运行auth.restrictToOwner

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

有两种选择。更容易的是不使用预制的钩子。几乎每个预先构建的钩子都可以通过几行代码自行实现。它看起来像这样:

app.service('myservice').before({
  find(hook) {
    const { user } = hook.params;
    const {roles } = user;

    if(roles.indexOf('admin') !== -1 && roles.indexOf('super-admin') !== -1) {
      hook.params.query.userId = user._id;
    }
  }  
});

另一种方法是创建一个首先调用restrictToRoles的包装器挂钩,然后调用catches任何错误(注意它基本上比完全自己实现它的代码更多):

const restrictToRoles = auth.restrictToRoles({
  roles: ['admin', 'super-admin']
});
const restrictToOwner = auth.restrictToOwner({ ownerField: 'id' });

app.service('myservice').before({
  find(hook) {
    return restrictToRoles(hook).catch(() => restrictToOwner(hook));
  }  
});
相关问题