I have issues extending joi class with custom operators. I want to validate mongodb Ids, but the extended object throws following error:
error: uncaughtException: JoiObj.string(...).objectId is not a function
TypeError: JoiObj.string(...).objectId is not a function
Code is following:
import Joi from 'joi';
import * as mongodb from 'mongodb';
interface ExtendedStringSchema extends Joi.StringSchema {
objectId(): this;
}
interface ExtendedJoi extends Joi.Root {
string(): ExtendedStringSchema;
}
const JoiObj: ExtendedJoi = Joi.extend({
base: Joi.string(),
type: 'objectId',
messages: {
'objectId.invalid': '"{{#label}}" must be a valid mongo id'
},
validate(value, helpers) {
if (!mongodb.ObjectId.isValid(value)) {
return helpers.error('objectId.invalid');
}
return value;
}
});
const objIdSchema = JoiObj.object({
id: JoiObj.string().objectId()
});
I found 2 examples:
https://github.com/sideway/joi/issues/2357
How to extend a module from npm using TypeScript?
however they use different properties than what is described in TS definition file and thus does not work.