|
| 1 | +import { |
| 2 | + createParamDecorator, |
| 3 | + type ExecutionContext, |
| 4 | + BadRequestException, |
| 5 | +} from '@nestjs/common' |
| 6 | +import type { z } from 'zod' |
| 7 | +import { ZodError } from 'zod' |
| 8 | +import type { Request } from 'express' |
| 9 | +import { ApiBody, ApiQuery, ApiParam } from '@nestjs/swagger' |
| 10 | +import { zodToOpenAPI } from './swagger.decorators.js' |
| 11 | + |
| 12 | +const SKIP_STRICT = Symbol('SKIP_STRICT') |
| 13 | +type SchemaWithMetadata = z.ZodType & { [SKIP_STRICT]?: boolean } |
| 14 | + |
| 15 | +// Cache strict schemas to avoid recreating them on every request |
| 16 | +const strictSchemaCache = new WeakMap<z.ZodType, z.ZodType>() |
| 17 | + |
| 18 | +export function allowUnknown<T extends z.ZodType>(schema: T): T { |
| 19 | + ;(schema as SchemaWithMetadata)[SKIP_STRICT] = true |
| 20 | + return schema |
| 21 | +} |
| 22 | + |
| 23 | +function getStrictSchema(schema: z.ZodType): z.ZodType { |
| 24 | + const schemaWithMeta = schema as SchemaWithMetadata |
| 25 | + |
| 26 | + if (schemaWithMeta[SKIP_STRICT] === true) { |
| 27 | + return schema |
| 28 | + } |
| 29 | + |
| 30 | + if (!('strict' in schema && typeof schema.strict === 'function')) { |
| 31 | + return schema |
| 32 | + } |
| 33 | + |
| 34 | + let cached = strictSchemaCache.get(schema) |
| 35 | + if (!cached) { |
| 36 | + cached = (schema.strict as () => z.ZodType)() |
| 37 | + strictSchemaCache.set(schema, cached) |
| 38 | + } |
| 39 | + return cached |
| 40 | +} |
| 41 | + |
| 42 | +/** Validates `request.body` with the given Zod schema and injects Swagger metadata. */ |
| 43 | +export function ParseBody(schema: z.ZodType) { |
| 44 | + const paramDecorator = createParamDecorator((_data: unknown, ctx: ExecutionContext) => { |
| 45 | + const request = ctx.switchToHttp().getRequest<Request>() |
| 46 | + try { |
| 47 | + return getStrictSchema(schema).parse(request.body) |
| 48 | + } catch (error) { |
| 49 | + if (error instanceof ZodError) throw error |
| 50 | + throw new BadRequestException('Validation failed') |
| 51 | + } |
| 52 | + })() |
| 53 | + |
| 54 | + return (target: object, propertyKey: string | symbol, parameterIndex: number) => { |
| 55 | + paramDecorator(target, propertyKey, parameterIndex) |
| 56 | + |
| 57 | + const openApiSchema = zodToOpenAPI(schema) |
| 58 | + const descriptor = Object.getOwnPropertyDescriptor(target, propertyKey) |
| 59 | + if (descriptor && openApiSchema) { |
| 60 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment |
| 61 | + ApiBody({ schema: openApiSchema as any })(target, propertyKey, descriptor) |
| 62 | + } |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +/** Validates `request.query` with the given Zod schema and injects Swagger metadata. */ |
| 67 | +export function ParseQuery(schema: z.ZodType) { |
| 68 | + const paramDecorator = createParamDecorator((_data: unknown, ctx: ExecutionContext) => { |
| 69 | + const request = ctx.switchToHttp().getRequest<Request>() |
| 70 | + try { |
| 71 | + return schema.parse(request.query) |
| 72 | + } catch (error) { |
| 73 | + if (error instanceof ZodError) throw error |
| 74 | + throw new BadRequestException('Validation failed') |
| 75 | + } |
| 76 | + })() |
| 77 | + |
| 78 | + return (target: object, propertyKey: string | symbol, parameterIndex: number) => { |
| 79 | + paramDecorator(target, propertyKey, parameterIndex) |
| 80 | + |
| 81 | + const openApiSchema = zodToOpenAPI(schema) |
| 82 | + const descriptor = Object.getOwnPropertyDescriptor(target, propertyKey) |
| 83 | + |
| 84 | + if ( |
| 85 | + descriptor && |
| 86 | + openApiSchema && |
| 87 | + 'type' in openApiSchema && |
| 88 | + openApiSchema['type'] === 'object' && |
| 89 | + 'properties' in openApiSchema |
| 90 | + ) { |
| 91 | + const properties = openApiSchema['properties'] as Record<string, unknown> |
| 92 | + const requiredFields = (openApiSchema['required'] as string[] | undefined) ?? [] |
| 93 | + |
| 94 | + for (const [key, propSchema] of Object.entries(properties)) { |
| 95 | + const isRequired = requiredFields.includes(key) |
| 96 | + const desc = (propSchema as { description?: string }).description |
| 97 | + |
| 98 | + ApiQuery({ |
| 99 | + name: key, |
| 100 | + required: isRequired, |
| 101 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment |
| 102 | + schema: propSchema as any, |
| 103 | + ...(desc ? { description: desc } : {}), |
| 104 | + })(target, propertyKey, descriptor) |
| 105 | + } |
| 106 | + } |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +/** Validates `request.params` with the given Zod schema and injects Swagger metadata. */ |
| 111 | +export function ParseParams(schema: z.ZodType) { |
| 112 | + const paramDecorator = createParamDecorator((_data: unknown, ctx: ExecutionContext) => { |
| 113 | + const request = ctx.switchToHttp().getRequest<Request>() |
| 114 | + try { |
| 115 | + return schema.parse(request.params) |
| 116 | + } catch (error) { |
| 117 | + if (error instanceof ZodError) throw error |
| 118 | + throw new BadRequestException('Validation failed') |
| 119 | + } |
| 120 | + })() |
| 121 | + |
| 122 | + return (target: object, propertyKey: string | symbol, parameterIndex: number) => { |
| 123 | + paramDecorator(target, propertyKey, parameterIndex) |
| 124 | + |
| 125 | + const openApiSchema = zodToOpenAPI(schema) |
| 126 | + const descriptor = Object.getOwnPropertyDescriptor(target, propertyKey) |
| 127 | + |
| 128 | + if ( |
| 129 | + descriptor && |
| 130 | + openApiSchema && |
| 131 | + 'type' in openApiSchema && |
| 132 | + openApiSchema['type'] === 'object' && |
| 133 | + 'properties' in openApiSchema |
| 134 | + ) { |
| 135 | + const properties = openApiSchema['properties'] as Record<string, unknown> |
| 136 | + for (const [key, propSchema] of Object.entries(properties)) { |
| 137 | + const desc = (propSchema as { description?: string }).description |
| 138 | + |
| 139 | + ApiParam({ |
| 140 | + name: key, |
| 141 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-assignment |
| 142 | + schema: propSchema as any, |
| 143 | + ...(desc ? { description: desc } : {}), |
| 144 | + })(target, propertyKey, descriptor) |
| 145 | + } |
| 146 | + } |
| 147 | + } |
| 148 | +} |
0 commit comments