fix(zod-validator): support transform (#1315)

* fix(zod-validator): support transform

* polish
pull/1317/head
Yusuke Wada 2025-07-19 10:20:40 +09:00 committed by GitHub
parent 1a564d5fb6
commit c6a16ab7aa
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 42 additions and 1 deletions

View File

@ -0,0 +1,5 @@
---
'@hono/zod-validator': patch
---
fix: support transform

View File

@ -73,7 +73,7 @@ export const zValidator = <
if ((target === 'header' && '_def' in schema) || (target === 'header' && '_zod' in schema)) { if ((target === 'header' && '_def' in schema) || (target === 'header' && '_zod' in schema)) {
// create an object that maps lowercase schema keys to lowercase // create an object that maps lowercase schema keys to lowercase
// @ts-expect-error the schema is a Zod Schema // @ts-expect-error the schema is a Zod Schema
const schemaKeys = Object.keys(schema.shape) const schemaKeys = Object.keys('in' in schema ? schema.in.shape : schema.shape)
const caseInsensitiveKeymap = Object.fromEntries( const caseInsensitiveKeymap = Object.fromEntries(
schemaKeys.map((key) => [key.toLowerCase(), key]) schemaKeys.map((key) => [key.toLowerCase(), key])
) )

View File

@ -464,3 +464,39 @@ describe('With options + validationFunction', () => {
}) })
}) })
}) })
describe('Transform', () => {
const schema = z
.object({
'user-agent': z.string(),
})
.transform((data) => ({
userAgent: data['user-agent'],
}))
const zValidatorHeader = zValidator('header', schema)
const app = new Hono()
app.post('/test', zValidatorHeader, async (c) => {
const header = c.req.valid('header')
return c.json(header)
})
it('Should return 400 response', async () => {
const res = await app.request('/test', {
method: 'POST',
})
expect(res.status).toBe(400)
})
it('Should return 200 response', async () => {
const res = await app.request('/test', {
method: 'POST',
headers: {
'user-agent': 'my-agent',
},
})
expect(res.status).toBe(200)
})
})