|
| 1 | +import 'reflect-metadata' |
| 2 | +import { validator } from 'hono/validator' |
| 3 | +import { ClassConstructor, ClassTransformOptions, plainToClass } from 'class-transformer' |
| 4 | +import { Context, Env, Input, MiddlewareHandler, TypedResponse, ValidationTargets } from 'hono' |
| 5 | +import { ValidationError, validate } from 'class-validator' |
| 6 | + |
| 7 | +/** |
| 8 | + * Hono middleware that validates incoming data using class-validator(https://github.com/typestack/class-validator). |
| 9 | + * |
| 10 | + * --- |
| 11 | + * |
| 12 | + * No Hook |
| 13 | + * |
| 14 | + * ```ts |
| 15 | + * import { classValidator } from '@hono/class-validator' |
| 16 | + * import { IsInt, IsString } from 'class-validator' |
| 17 | + * |
| 18 | + * class CreateUserDto { |
| 19 | + * @IsString() |
| 20 | + * name!: string; |
| 21 | + * |
| 22 | + * @IsInt() |
| 23 | + * age!: number; |
| 24 | + * } |
| 25 | + * |
| 26 | + * |
| 27 | + * const route = app.post('/user', classValidator('json', CreateUserDto), (c) => { |
| 28 | + * const user = c.req.valid('json') |
| 29 | + * return c.json({ success: true, message: `${user.name} is ${user.age}` }) |
| 30 | + * }) |
| 31 | + * ``` |
| 32 | + * |
| 33 | + * --- |
| 34 | + * Hook |
| 35 | + * |
| 36 | + * ```ts |
| 37 | + * import { classValidator } from '@hono/class-validator' |
| 38 | + * import { IsInt, IsString } from 'class-validator' |
| 39 | + * |
| 40 | + * class CreateUserDto { |
| 41 | + * @IsString() |
| 42 | + * name!: string; |
| 43 | + * |
| 44 | + * @IsInt() |
| 45 | + * age!: number; |
| 46 | + * } |
| 47 | + * |
| 48 | + * app.post( |
| 49 | + * '/user', |
| 50 | + * classValidator('json', CreateUserDto, (result, c) => { |
| 51 | + * if (!result.success) { |
| 52 | + * return c.text('Invalid!', 400) |
| 53 | + * } |
| 54 | + * }) |
| 55 | + * //... |
| 56 | + * ) |
| 57 | + * ``` |
| 58 | + */ |
| 59 | + |
| 60 | +type Hook< |
| 61 | + T, |
| 62 | + E extends Env, |
| 63 | + P extends string, |
| 64 | + Target extends keyof ValidationTargets = keyof ValidationTargets, |
| 65 | + O = object |
| 66 | +> = ( |
| 67 | + result: ({ success: true } | { success: false; errors: ValidationError[] }) & { |
| 68 | + data: T |
| 69 | + target: Target |
| 70 | + }, |
| 71 | + c: Context<E, P> |
| 72 | +) => Response | void | TypedResponse<O> | Promise<Response | void | TypedResponse<O>> |
| 73 | + |
| 74 | +type HasUndefined<T> = undefined extends T ? true : false |
| 75 | + |
| 76 | +type HasClassConstructor<T> = ClassConstructor<any> extends T ? true : false |
| 77 | + |
| 78 | +export type StaticObject<T extends ClassConstructor<any>> = { |
| 79 | + [K in keyof InstanceType<T>]: HasClassConstructor<InstanceType<T>[K]> extends true |
| 80 | + ? StaticObject<InstanceType<T>[K]> |
| 81 | + : InstanceType<T>[K] |
| 82 | +} |
| 83 | + |
| 84 | +const parseAndValidate = async <T extends ClassConstructor<any>>( |
| 85 | + dto: T, |
| 86 | + obj: object, |
| 87 | + options: ClassTransformOptions |
| 88 | +): Promise< |
| 89 | + { success: false; errors: ValidationError[] } | { success: true; output: InstanceType<T> } |
| 90 | +> => { |
| 91 | + // tranform the literal object to class object |
| 92 | + const objInstance = plainToClass(dto, obj, options) |
| 93 | + // validating and check the errors, throw the errors if exist |
| 94 | + |
| 95 | + const errors = await validate(objInstance) |
| 96 | + // errors is an array of validation errors |
| 97 | + if (errors.length > 0) { |
| 98 | + return { |
| 99 | + success: false, |
| 100 | + errors, |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + return { success: true, output: objInstance as InstanceType<T> } |
| 105 | +} |
| 106 | + |
| 107 | +export const classValidator = < |
| 108 | + T extends ClassConstructor<any>, |
| 109 | + Output extends InstanceType<T> = InstanceType<T>, |
| 110 | + Target extends keyof ValidationTargets = keyof ValidationTargets, |
| 111 | + E extends Env = Env, |
| 112 | + P extends string = string, |
| 113 | + In = StaticObject<T>, |
| 114 | + I extends Input = { |
| 115 | + in: HasUndefined<In> extends true |
| 116 | + ? { |
| 117 | + [K in Target]?: K extends 'json' |
| 118 | + ? In |
| 119 | + : HasUndefined<keyof ValidationTargets[K]> extends true |
| 120 | + ? { [K2 in keyof In]?: ValidationTargets[K][K2] } |
| 121 | + : { [K2 in keyof In]: ValidationTargets[K][K2] } |
| 122 | + } |
| 123 | + : { |
| 124 | + [K in Target]: K extends 'json' |
| 125 | + ? In |
| 126 | + : HasUndefined<keyof ValidationTargets[K]> extends true |
| 127 | + ? { [K2 in keyof In]?: ValidationTargets[K][K2] } |
| 128 | + : { [K2 in keyof In]: ValidationTargets[K][K2] } |
| 129 | + } |
| 130 | + out: { [K in Target]: Output } |
| 131 | + }, |
| 132 | + V extends I = I |
| 133 | +>( |
| 134 | + target: Target, |
| 135 | + dataType: T, |
| 136 | + hook?: Hook<Output, E, P, Target>, |
| 137 | + options: ClassTransformOptions = { enableImplicitConversion: false } |
| 138 | +): MiddlewareHandler<E, P, V> => |
| 139 | + // @ts-expect-error not typed well |
| 140 | + validator(target, async (data, c) => { |
| 141 | + const result = await parseAndValidate(dataType, data, options) |
| 142 | + |
| 143 | + if (hook) { |
| 144 | + const hookResult = hook({ ...result, data, target }, c) |
| 145 | + if (hookResult instanceof Response || hookResult instanceof Promise) { |
| 146 | + if ('response' in hookResult) { |
| 147 | + return hookResult.response |
| 148 | + } |
| 149 | + return hookResult |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + if (!result.success) { |
| 154 | + return c.json({ errors: result.errors }, 400) |
| 155 | + } |
| 156 | + |
| 157 | + return result.output |
| 158 | + }) |
0 commit comments