【问题标题】:Loopback: Create dynamic properties for model instanceLoopback:为模型实例创建动态属性
【发布时间】:2018-05-16 16:47:26
【问题描述】:

例如,我有一个环回模型名称 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';
}

我还希望在 Loopback REST API 的那些 JSON 响应中包含 status。谢谢大家。

【问题讨论】:

    标签: node.js loopbackjs loopback


    【解决方案1】:

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

    使用远程挂钩,

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

    这里,* 可以是任何端点的任何动作。详情请参考this

    使用操作钩子,

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

    【讨论】:

      【解决方案2】:

      我认为最简单的方法是使用remote hooks,如果适用,只需将属性添加到结果集中。解释文档:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多