【问题标题】:StrongLoop modify data before each get on modelStrongLoop 在每次上模型之前修改数据
【发布时间】:2016-07-11 18:19:45
【问题描述】:

我在 LoopBackJS 中有以下模型:

{
  "name": "member",
  "base": "PersistedModel",
  "properties": {
    "firstName": {
      "type": "string"
    }
    "public": {
      "type": "boolean"
    }
  },
  "relations": {
    "spouse": {
      "type": "hasOne",
      "model": "spouse",
      "foreignKey": "spouseId"
    }
  }
}

现在我需要修改firstName 字段,所以只能看到"public": true 成员的名字,而其他人则得到firstName: "*"。我已经拥有的功能。

但是如何访问每个数据访问请求中的数据?

我用操作钩子尝试了它,例如find, findOne,... 但是当我错过其中一个时,一些用户可以访问 firstName。 远程钩子也是一样。

现在我正在尝试使用连接器挂钩:

connector.observe('after execute', function(ctx, next) {
if (ctx.model === 'familyMember') {
    if (ctx.req.command === 'find') {
    }
  }
  next();
});

对于所有查找查询(mongodb),但我无法访问数据。有没有办法访问这些数据?还是有更好的(内置)解决方案来解决这个问题?

【问题讨论】:

    标签: loopbackjs strongloop


    【解决方案1】:

    您需要在每个遥控器后检查结果:

    member.afterRemote('**', function(ctx, modelInstance, next) {
      if (ctx.result) {
        if (Array.isArray(modelInstance)) {
          var answer = [];
          ctx.result.forEach(function (result) {
            if(result.public === false)
              result.firstName = "*";
            answer.push(result);
          });
        } else {     
          var answer =ctx.result;
          if(answer.public === false)
            answer.firstName = "*";  
        }
        ctx.result = answer;
      }
      next();
    });
    

    【讨论】:

    • 看起来不错。谢谢!
    猜你喜欢
    • 2017-05-03
    • 2014-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 2021-03-04
    • 2016-12-14
    相关资源
    最近更新 更多