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