Joi.extend 返回joi 模块的新实例,您可以使用导出的Root 类型。
您需要创建一个扩展Joi.Root 的接口和另一个扩展您要扩展的基本joi 类型的接口。您可以像导出任何其他对象一样简单地导出自定义 joi 实例。
下面是使用extend() 上的API Documentation 示例中的round() 和dividable() 规则的示例。
import * as Joi from 'joi';
interface ExtendedNumberSchema extends Joi.NumberSchema {
round(): this;
dividable(num: number): this;
}
interface ExtendedJoi extends Joi.Root {
number(): ExtendedNumberSchema;
}
const customJoi: ExtendedJoi = Joi.extend((joi) => ({
base: joi.number(),
name: 'number',
language: {
round: 'needs to be a rounded number', // Used below as 'number.round'
dividable: 'needs to be dividable by {{q}}'
},
pre(value, state, options) {
if (options.convert && this._flags.round) {
return Math.round(value); // Change the value
}
return value; // Keep the value as it was
},
rules: [
{
name: 'round',
setup(params) {
this._flags.round = true; // Set a flag for later use
},
validate(params, value, state, options) {
if (value % 1 !== 0) {
// Generate an error, state and options need to be passed
return this.createError('number.round', {v: value}, state, options);
}
return value; // Everything is OK
}
},
{
name: 'dividable',
params: {
q: joi.alternatives([joi.number().required(), joi.func().ref()])
},
validate(params, value, state, options) {
if (value % params.q !== 0) {
// Generate an error, state and options need to be passed, q is used in the language
return this.createError('number.dividable', {v: value, q: params.q}, state, options);
}
return value; // Everything is OK
}
}
]
}));
const schema = {
a: customJoi.number().round().dividable(3)
};
const result = customJoi.validate({a: 4.1}, schema); // will fail because 4 is no divisible by 3
console.log(result);
export = customJoi;