首页 文章

环回模型验证失败(异步行为)

提问于
浏览
1

我正在尝试验证模型及其内容 . 但是,由于loopbacks自定义验证函数的结构,编写比简单字符串验证更高级的逻辑非常困难 .

Job.validate('job_definition, function(err){
    //err();
    //this will succeed in throwing error
    Job.app.models.anotherModel.findOne({where:{name:this.job_definition.toolName}}, function(error, tool){
      if(tool.aProperty === this.job_definition.aProperty){
          //err();
          //this will not succeed, validation script will exit before err() is thrown
      }
    });
}, {message: 'this is malformed'});

如何让这个验证功能在退出前“等待”?

1 回答

  • 3

    以下是使用validateAsync(https://apidocs.strongloop.com/loopback-datasource-juggler/#validatable-validateasync)的示例 . 请注意,如果要验证失败,则必须运行err() .

    module.exports = function(Person) {
    
        function myCustom(err, done) {
            console.log('async validate');
            var name = this.name;
            setTimeout(function() {
                if(name == 'Ray') {
                    err();
                    done();
                } else {
                    done();
                }
    
            }, 1000);   
        }
    
        Person.validateAsync('name', myCustom, {message:'Dont like'});
    
    };
    

    这有意义吗?仅供参考,我可以改写一下,如果更好一点 .

相关问题