首页 > 解决方案 > Loopback:为模型实例创建动态属性

问题描述

例如,我有一个回送模型名称Event,它有 2 个属性,如下所示:

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

如何status使用如下逻辑添加动态属性名称:

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

我也想status在那些 JSON 响应中包含 Loopback REST API。多谢你们。

标签: node.jsloopbackjsloopback

解决方案


如果ctx在远程挂钩或操作挂钩中添加所需的属性,该属性将被添加到模型中并保存到数据库中。

使用远程挂钩,

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

在这里,* 可以是任何端点的任何动作。有关更多详细信息,请参阅

使用操作挂钩,

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

推荐阅读