Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(zod-openapi): implement Zod schema validation on response #184

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/itchy-games-fail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hono/zod-openapi': minor
---

add response Zod schema validation on response
55 changes: 55 additions & 0 deletions packages/zod-openapi/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,8 @@ type HandlerResponse<O> = TypedResponse<O> | Promise<TypedResponse<O>>

export type OpenAPIHonoOptions<E extends Env> = {
defaultHook?: Hook<any, E, any, any>
strictStatusCode?: boolean
strictResponse?: boolean
}
type HonoInit<E extends Env> = ConstructorParameters<typeof Hono>[0] & OpenAPIHonoOptions<E>

Expand Down Expand Up @@ -187,11 +189,15 @@ export class OpenAPIHono<
> extends Hono<E, S, BasePath> {
openAPIRegistry: OpenAPIRegistry
defaultHook?: OpenAPIHonoOptions<E>['defaultHook']
strictStatusCode?: OpenAPIHonoOptions<E>['strictStatusCode']
strictResponse?: OpenAPIHonoOptions<E>['strictResponse']

constructor(init?: HonoInit<E>) {
super(init)
this.openAPIRegistry = new OpenAPIRegistry()
this.defaultHook = init?.defaultHook
this.strictStatusCode = init?.strictStatusCode
this.strictResponse = init?.strictResponse
}

openapi = <
Expand Down Expand Up @@ -256,6 +262,55 @@ export class OpenAPIHono<
}
}

if (this.strictResponse) {
const responseZodSchemaObject: Record<string, ZodType<any>> = {}
for (const [statusCode, responseConfig] of Object.entries(route.responses)) {
for (const mediaTypeObject of Object.values(responseConfig.content ?? {})) {
if (mediaTypeObject.schema instanceof ZodType) {
responseZodSchemaObject[statusCode] = mediaTypeObject.schema
}
}
}

if (Object.keys(responseZodSchemaObject).length > 0) {
validators.push(async (c, next) => {
await next()

const schema = responseZodSchemaObject[c.res.status]
if (schema) {
const originalBody = await c.res.json()
const result = await schema.safeParseAsync(originalBody)
if (!result.success) {
c.res = c.json(result.error, {
status: 500,
})
} else {
c.res = c.json(result.data)
}
}
})
}
}

if (this.strictStatusCode) {
validators.push(async (c, next) => {
await next()

if (!route.responses[c.res.status]) {
c.res = c.json(
{
success: false,
error: 'Response code does not match any of the defined responses.',
},
{
status: 500,
}
)
return
}
})
}

this.on([route.method], route.path.replaceAll(/\/{(.+?)}/g, '/:$1'), ...validators, handler)
return this
}
Expand Down