Joi:自动验证函数参数 [英] Joi: Automatic validation of function arguments
问题描述
我看到一个使用 joi
库的代码库,如下所示:
I saw a codebase which was using joi
library like this:
function f(a, b) {
// ...
}
f.schema = {
a: Joi.string().uuid().required(),
b: Joi.number()
}
然后 f.schema
属性没有在其他任何地方被引用.是否有一些框架使用 schema
属性自动验证函数参数?谷歌搜索这没有提出任何东西.
And then the f.schema
property wasn't referenced anywhere else. Is there some framework which performs automatic validation of function arguments using the schema
property? Googling this didn't bring up anything.
推荐答案
我认为不可能完全按照您在此处显示的内容进行操作,因为 在 Javascript 中不可能重载函数调用,但有一种方法可以做一些非常相似的事情使用代理.
I don't think it is possible to do exactly what you are showing here, since overloading of function call is impossible in Javascript, but there is a way to do something pretty similar using Proxies.
这是我设法做到的.我们创建了一个 validated
代理对象,它覆盖了 apply
行为,它对应于标准函数调用,以及 apply
和 call
方法.
Here is what I've managed to do. We create a validated
proxy object, that overrides the apply
behavior, which corresponds to standard function calls, as well as apply
and call
methods.
代理检查函数上是否存在 schema
属性,然后使用 schema
数组的元素验证每个参数.
The proxy checks for the presence of a schema
property on the function, then validates each argument using the elements of the schema
array.
const Joi = require('joi');
const validated = function(f) {
return new Proxy(f, {
apply: function(target, thisArg, arguments) {
if (target.schema) {
for (let i = 0; i < target.length; i++) {
const res = target.schema[i].validate(arguments[i]);
if (res.error) {
throw res.error;
}
}
}
target.apply(thisArg, arguments)
}
})
}
const myFunc = validated((a, b) => {
console.log(a, b)
});
myFunc.schema = [
Joi.string().required(),
Joi.number(),
];
myFunc('a', 2);
这篇关于Joi:自动验证函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!