环回模型验证失败(异步行为)
loopback model validation failures (asynchronous behavior)
我正在尝试验证模型及其内容。但是,由于环回自定义验证函数的结构,编写比简单字符串验证更高级的逻辑非常困难。
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'});
如何在退出前将此验证函数设置为 'wait'?
这是一个使用 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'});
};
这有意义吗?仅供参考,如果更好一点,我可以重写它。
我正在尝试验证模型及其内容。但是,由于环回自定义验证函数的结构,编写比简单字符串验证更高级的逻辑非常困难。
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'});
如何在退出前将此验证函数设置为 'wait'?
这是一个使用 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'});
};
这有意义吗?仅供参考,如果更好一点,我可以重写它。