|
| 1 | +import "reflect-metadata"; |
| 2 | +import type { MiddlewareHandler, ValidationTargets } from "hono"; |
| 3 | +import { validator as honoValidator } from "hono/validator"; |
| 4 | +import { z } from "zod"; |
| 5 | +import { MetadataMiddlewareConstant } from "App/Types/ControllerConstant.js"; |
| 6 | +import type Controller from "Controller/Controller.js"; |
| 7 | +import { onValidateError } from "Function/OnValidateError.js"; |
| 8 | + |
| 9 | +export type ZodData<V> = { [VK in keyof V]: any }; |
| 10 | + |
| 11 | +function reflectingMetadata(target: Function, func: MiddlewareHandler): void { |
| 12 | + if (!Reflect.hasMetadata(MetadataMiddlewareConstant, target)) { |
| 13 | + Reflect.defineMetadata(MetadataMiddlewareConstant, [func], target); |
| 14 | + return; |
| 15 | + } |
| 16 | + |
| 17 | + const metadata = Reflect.getMetadata(MetadataMiddlewareConstant, target) as MiddlewareHandler[]; |
| 18 | + metadata.push(func); |
| 19 | + |
| 20 | + Reflect.deleteMetadata(MetadataMiddlewareConstant, target); |
| 21 | + Reflect.defineMetadata(MetadataMiddlewareConstant, metadata, target); |
| 22 | +} |
| 23 | + |
| 24 | +/** |
| 25 | + * Validate data for route. |
| 26 | + * |
| 27 | + * @param method - Target of request |
| 28 | + * @param data - Data to validate |
| 29 | + */ |
| 30 | +export function validator<T extends {}>(method: keyof ValidationTargets, data: ZodData<T>): Function { |
| 31 | + return function decorate(target: Controller, propKey: string, descriptor: PropertyDescriptor): void { |
| 32 | + const targetFunc = descriptor.value as Function; |
| 33 | + const funcValidator = honoValidator(method, (val, c) => { |
| 34 | + const parsed = z.object(data).safeParse(val); |
| 35 | + if (!parsed.success) return onValidateError(c, data); |
| 36 | + return parsed.data; |
| 37 | + }); |
| 38 | + reflectingMetadata(targetFunc, funcValidator); |
| 39 | + }; |
| 40 | +} |
| 41 | + |
| 42 | +/** |
| 43 | + * Add middleware on route. |
| 44 | + * |
| 45 | + * @param handlers - Middleware handlers for route |
| 46 | + * @see MiddlewareHandler |
| 47 | + */ |
| 48 | +export function middleware(...handlers: MiddlewareHandler[] | Promise<MiddlewareHandler>[] | Promise<void>[]): Function { |
| 49 | + return function decorate(target: Controller, propKey: string, descriptor: PropertyDescriptor): void { |
| 50 | + const targetFunc = descriptor.value as Function; |
| 51 | + for (const handler of handlers) { |
| 52 | + const targetHandler = handler as MiddlewareHandler; |
| 53 | + reflectingMetadata(targetFunc, targetHandler); |
| 54 | + } |
| 55 | + }; |
| 56 | +} |
0 commit comments