Dũng Nguyễn
Dũng Nguyễn

Reputation: 495

Loopback: Create dynamic properties for model instance

For example I have a loopback model name Event and it has 2 properties like this:

...
"properties": {
  "name": {
    "type": "string",
    "required": true
  },
  "end": {
    "type": "date",
    "required": false
  }
}...

How can I add a dynamic property name status with logic like this:

if (now() > this.end) {
  this.status = 'end';
} else {
  this.status = 'running';
}

Also I want to have status in those JSON responses for Loopback REST API as well. Thanks guys.

Upvotes: 0

Views: 867

Answers (2)

20B2
20B2

Reputation: 2141

If you add the required property the ctx in the remote hook or the operation hook, the property will be added to the model and saved to the database.

Using remote hook,

Event.beforeRemote('*', (ctx, modelInstance, next) => {
    ctx.req.body.propertyName = propertyValue;
    ...
    next();
});

Here, * can be any action for any endpoint. Refer this for more details.

Using Operation hook,

Event.observe('before save', (ctx, next) => {
   //for insert, full update
   if(ctx.instance) {
       ctx.instance.propertyName = propertyValue;
       ...
       return next();
   } 
   // for partial update
   else if(ctx.data) { 
       ctx.data.propertyName = propertyValue;
       ...
       return next();
   }
}); 

Upvotes: 1

user8120138
user8120138

Reputation:

I think the easiest way to do this is with remote hooks and simply add the property to the result set if applicable. To paraphrase the documentation:

Event.afterRemote('**', function (ctx, user, next) {
  const now = new Date();
  if(ctx.result) {
    if(Array.isArray(ctx.result)) {
      ctx.result.forEach(function (result) {
        result.status = now > result.end ? 'end' : 'running';
      });
    } else {
      result.status = now > result.end ? 'end' : 'running';
    }
  }

  next();
});

Upvotes: 0

Related Questions