Joi: Automatic validation of function arguments

佐手、 提交于 2021-02-10 05:36:47

问题


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

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.


回答1:


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.

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.

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


来源:https://stackoverflow.com/questions/61897947/joi-automatic-validation-of-function-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!