Open WangHansen opened 4 years ago
I'm not a Typescript fan, so I don't bother with it. But you are welcome to open a PR with TypeScript definitions etc.
Here example for TypeScript + TypeOrm + NestJs
export const JoiObjectId: ExtensionFactory = (joi) => ({
type: 'objectId',
base: joi.any().meta({ baseType: 'string' }),
messages: {
objectId: 'needs to be a valid ObjectId',
},
coerce: (value) => {
if (!value) {
return;
}
if (ObjectId.isValid(value)) {
return { value: new ObjectId(value) };
}
return value;
},
validate(value, helpers) {
if (!(value instanceof ObjectId)) {
const errors = helpers.error('objectId');
return {value, errors};
}
},
});
interface ObjectIdJoi extends JoiBase.StringSchema {
objectId(): this;
}
export const Joi = JoiBase.extend(JoiObjectId) as typeof JoiBase & ObjectIdJoi;
export class JoiValidationPipe<T> implements PipeTransform {
constructor(private schema: JoiBase.ObjectSchema) { }
public transform(oldValue: unknown): T {
const { error, value } = this.schema.validate(oldValue, {
convert: true,
allowUnknown: true,
});
if (error) {
const errors = error.details.map((item) => {
return item.message;
});
throw new CommonValidationException(String(errors));
}
return value as T;
}
}```
@hapi/joi
has type definitions here: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/hapi__joi/index.d.tsI was wondering how to use this extension with typescript?