@@ -11,7 +11,6 @@ import type { ZodAny } from 'zod'
1111import { Is } from '@athenna/common'
1212import type { FastifyReply , FastifyRequest , FastifySchema } from 'fastify'
1313import { ZodValidationException } from '#src/exceptions/ZodValidationException'
14- import { ResponseValidationException } from '#src/exceptions/ResponseValidationException'
1514
1615type ZodRequestSchema = Partial <
1716 Record < 'body' | 'headers' | 'params' | 'querystring' , ZodAny >
@@ -34,11 +33,13 @@ export type RouteZodSchemas = {
3433
3534export function normalizeRouteSchema ( options : RouteSchemaOptions ) : {
3635 schema : FastifySchema
36+ swaggerSchema : FastifySchema
3737 zod : RouteZodSchemas | null
3838} {
3939 const request : ZodRequestSchema = { }
4040 const response : ZodResponseSchema = { }
4141 const schema : FastifySchema = { ...options }
42+ const swaggerSchema : FastifySchema = { ...options }
4243
4344 const requestKeys = [ 'body' , 'headers' , 'params' , 'querystring' ] as const
4445
@@ -49,26 +50,34 @@ export function normalizeRouteSchema(options: RouteSchemaOptions): {
4950
5051 request [ key ] = options [ key ]
5152 schema [ key ] = toJsonSchema ( options [ key ] , 'input' )
53+ swaggerSchema [ key ] = toJsonSchema ( options [ key ] , 'input' )
5254 } )
5355
5456 if ( options . response && Is . Object ( options . response ) ) {
5557 schema . response = { ...options . response }
58+ swaggerSchema . response = { ...options . response }
5659
5760 Object . entries ( options . response ) . forEach ( ( [ statusCode , value ] ) => {
5861 if ( ! isZodSchema ( value ) ) {
5962 return
6063 }
6164
6265 response [ statusCode ] = value
63- schema . response [ statusCode ] = toJsonSchema ( value , 'output' )
66+ swaggerSchema . response [ statusCode ] = toJsonSchema ( value , 'output' )
67+ delete schema . response [ statusCode ]
6468 } )
69+
70+ if ( ! Object . keys ( schema . response ) . length ) {
71+ delete schema . response
72+ }
6573 }
6674
6775 const hasZodSchemas =
6876 Object . keys ( request ) . length > 0 || Object . keys ( response ) . length > 0
6977
7078 return {
7179 schema,
80+ swaggerSchema,
7281 zod : hasZodSchemas ? { request, response } : null
7382 }
7483}
@@ -107,9 +116,9 @@ export async function parseResponseWithZod(
107116 return payload
108117 }
109118
110- return parseSchema ( schema , payload ) . catch ( error => {
111- throw new ResponseValidationException ( error )
112- } )
119+ const result = await schema . safeParseAsync ( payload )
120+
121+ return result . success ? result . data : payload
113122}
114123
115124function getResponseSchema (
0 commit comments