feat(zod-validator): support enum types for `query` (#763)

* fix(zod-validator): support enum types for `query`

* add changeset
pull/764/head
Yusuke Wada 2024-10-06 13:24:53 +09:00 committed by GitHub
parent 3d78fa470d
commit 2a45247d80
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 41 additions and 8 deletions

View File

@ -0,0 +1,5 @@
---
'@hono/zod-validator': minor
---
feat: support enum types for `query`

View File

@ -27,17 +27,13 @@ export const zValidator = <
I extends Input = { I extends Input = {
in: HasUndefined<In> extends true in: HasUndefined<In> extends true
? { ? {
[K in Target]?: K extends 'json' [K in Target]?: In extends ValidationTargets[K]
? In ? In
: HasUndefined<keyof ValidationTargets[K]> extends true : { [K2 in keyof In]?: ValidationTargets[K][K2] }
? { [K2 in keyof In]?: ValidationTargets[K][K2] }
: { [K2 in keyof In]: ValidationTargets[K][K2] }
} }
: { : {
[K in Target]: K extends 'json' [K in Target]: In extends ValidationTargets[K]
? In ? In
: HasUndefined<keyof ValidationTargets[K]> extends true
? { [K2 in keyof In]?: ValidationTargets[K][K2] }
: { [K2 in keyof In]: ValidationTargets[K][K2] } : { [K2 in keyof In]: ValidationTargets[K][K2] }
} }
out: { [K in Target]: Out } out: { [K in Target]: Out }

View File

@ -49,7 +49,7 @@ describe('Basic', () => {
} & { } & {
query?: query?:
| { | {
name?: string | string[] | undefined name?: string | undefined
} }
| undefined | undefined
} }
@ -307,3 +307,35 @@ describe('With target', () => {
) )
}) })
}) })
describe('Only Types', () => {
it('Should return correct enum types for query', () => {
const app = new Hono()
const querySchema = z.object({
order: z.enum(['asc', 'desc']),
})
const route = app.get('/', zValidator('query', querySchema), (c) => {
const data = c.req.valid('query')
return c.json(data)
})
type Actual = ExtractSchema<typeof route>
type Expected = {
'/': {
$get: {
input: {
query: {
order: 'asc' | 'desc'
}
}
output: {
order: 'asc' | 'desc'
}
}
}
}
type verify = Expect<Equal<Expected, Actual>>
})
})