Loopback:隐藏一些用户角色的一些属性

Loopback: Hide some properties for some user roles

有这样的模型

{
  name,
  budget
}

还有一个角色reviewer

有什么方法可以隐藏 reviewerbudget 字段吗?

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

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