首页 文章

环回:隐藏某些用户角色的某些属性

提问于
浏览
1

有这样的模型

{
  name,
  budget
}

并且有一个角色 reviewer

有没有办法隐藏 reviewerbudget 字段?

1 回答

  • 2

    您可以为该模型使用远程钩子 . 例如,您的代码可能如下所示:

    MyModel.afterRemote('**', function(ctx, modelInstance, next) {
      if (ctx.result) {
        if (checkIfUserHasRole('reviewer')) { // <-- you need to implement this function
          // if you are going to return a list of items, eg. from Model.find(...) 
          if (Array.isArray(modelInstance)) { 
            ctx.result = ctx.result.map(item => {
              return modifyYourProperties(item); // <-- you need to implement this function
            }
          }
          // if you are going to return a single item, eg. from Model.findById(...)
          else {
            ctx.result = modifyYourProperties(ctx.result); // <-- as above...
            }
    
          });
        }
      }
      next();
    }
    

    现在,在对模型的每次远程调用中,您都可以修改结果 . 它们已经处理但尚未返回给请求者,因此您可以在此处隐藏所需的属性 .

    当然,您需要实现方法 checkIfUserHasRolemodifyYourProperties 来完成您要实现的目标 . 您可以在此处阅读有关远程挂钩的更多信息:https://loopback.io/doc/en/lb3/Remote-hooks.html

相关问题