Piu130
Piu130

Reputation: 1417

StrongLoop modify data before each get on model

I have the following model in LoopBackJS:

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

Now I need to modify the firstName field, so one can only see "public": true members first name and the others gets firstName: "*". The function for that I have already.

But how can I access the data on each data-access-request?

I tried it with the with the operation hook e.g. find, findOne,... but when I miss one of them some users could access the firstName. With the remote hook it's the same.

Now I'm trying it with the connector hook:

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

For all find queries (mongodb) but there I can't access the data. Is there a way to access those data? Or is there a much better (build-in) solution for this problem?

Upvotes: 1

Views: 67

Answers (1)

Ebrahim Pasbani
Ebrahim Pasbani

Reputation: 9396

You need to check result after each remote :

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

Upvotes: 1

Related Questions