runable tests and yarn changeset

pull/1130/head
migawka 2025-04-19 00:22:33 +02:00
parent 73c961310a
commit c8b2f10eee
3 changed files with 94 additions and 5 deletions

View File

@ -0,0 +1,5 @@
---
'@hono/zod-validator': minor
---
Added optional opt field for passthrough and might further editions, passthrough and tests to it

View File

@ -378,3 +378,87 @@ describe('Case-Insensitive Headers', () => {
type verify = Expect<Equal<Expected, Actual>>
})
})
describe('With options + passthrough', () => {
const app = new Hono()
const jsonSchema = z.object({
name: z.string(),
age: z.number()
});
const route = app.post(
'/',
zValidator('json', jsonSchema),
(c) => {
const data = c.req.valid('json')
return c.json({
success: true,
data
})
}
).post('/extended',
zValidator('json', jsonSchema, undefined, {
passthroughObject: true
}),
(c) => {
const data = c.req.valid('json')
return c.json({
success: true,
data
})
}
)
it('Should be ok due to passthrough schema', async () => {
const req = new Request('http://localhost/extended', {
body: JSON.stringify({
name: 'Superman',
age: 20,
length: 170,
weight: 55
}),
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
})
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
success: true,
data: {
name: "Superman",
age: 20,
length: 170,
weight: 55
}
})
})
it('Should be ok due to required schema', async () => {
const req = new Request('http://localhost', {
body: JSON.stringify({
name: 'Superman',
age: 20,
}),
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
})
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(await res.json()).toEqual({
success: true,
data: {
name: "Superman",
age: 20
}
})
})
})

View File

@ -65,7 +65,7 @@ export const zValidator = <
}
let result: z.infer<T>;
if (opt && "passthrough" in opt) {
if (opt && "passthroughObject" in opt) {
result = await schema.passthrough().safeParseAsync(validatorValue)
} else {
result = await schema.safeParseAsync(validatorValue)