adamreisnz / joi-object-id

A Joi extension to validation MongoDB ObjectId formats
MIT License
3 stars 3 forks source link

How to use with typescript? #1

Open WangHansen opened 4 years ago

WangHansen commented 4 years ago

@hapi/joi has type definitions here: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/hapi__joi/index.d.ts

I was wondering how to use this extension with typescript?

屏幕快照 2019-11-14 下午6 58 45
adamreisnz commented 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.

StagnantIce commented 10 months ago

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;
    }
}```