【问题标题】:LoopBack: Setting Required Fields at a Later TimeLoopBack:稍后设置必填字段
【发布时间】:2016-06-07 08:29:03
【问题描述】:

我遇到了一种情况,如果“类型”值为“在线”,我希望“电子邮件”属性是必需的。在一般的观点中,我有一个可能需要或不需要的字段,具体取决于另一个字段值。我将如何解决这种情况?

"properties": {
    "type": {
      "type": "string",
      "required": true
    },
    "email": {
      "type": "string"
      "required": //true or false depending on what 'type' is
    }
  }

【问题讨论】:

  • 我更新了我的代码以接受潜在的多个模型的部分更新。这样你就安全了。

标签: json node.js dependencies loopbackjs required


【解决方案1】:

将所有可能不需要的字段声明为非必需字段,并使用operation hook before save 来验证自定义逻辑功能中的字段。

在您的 model.js 文件中,使用您需要的逻辑实现挂钩。例如,如果类型是“A”并且需要电子邮件但请求中没有提供,则生成错误并调用next(err)。这样,请求将被拒绝。

MyModel.observe('before create', function(ctx, next) {
    if(ctx.instance){
        data = ctx.instance
    } else {
        data = ctx.data
    {
    if(data.type =='A' && !data.email){
        next(new Error('No email provided !')
    } else {
       next();
    }
});

【讨论】:

    【解决方案2】:

    清理@overdriver 的代码,使其更易于实现

      MyModel.observe('before save', (ctx, next) => {
        let obj = ctx.instance;
    
        if(obj.type == 'A' && obj.email == null){
            next(new Error('No email provided !'));
        }
        else {
            next();
        }
      });
    

    【讨论】:

    • 已将您的反馈考虑在内。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 2016-06-12
    • 2011-12-02
    • 2018-01-06
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多