fix(zod-validator): passing data to hook (#107)

* fix(zod-validator): passing data to hook

* changeset
pull/108/head
Yusuke Wada 2023-08-07 22:30:49 +09:00 committed by GitHub
parent fb34f25205
commit 8eb3967477
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 9 additions and 3 deletions

View File

@ -0,0 +1,5 @@
---
'@hono/zod-validator': patch
---
fix passing data to hook

View File

@ -3,7 +3,7 @@ import { validator } from 'hono/validator'
import type { z, ZodSchema, ZodError } from 'zod' import type { z, ZodSchema, ZodError } from 'zod'
type Hook<T, E extends Env, P extends string> = ( type Hook<T, E extends Env, P extends string> = (
result: { success: true; data: T } | { success: false; error: ZodError }, result: { success: true; data: T } | { success: false; error: ZodError; data: T },
c: Context<E, P> c: Context<E, P>
) => Response | Promise<Response> | void | Promise<Response | void> ) => Response | Promise<Response> | void | Promise<Response | void>
@ -28,7 +28,7 @@ export const zValidator = <
const result = schema.safeParse(value) const result = schema.safeParse(value)
if (hook) { if (hook) {
const hookResult = hook(result, c) const hookResult = hook({ data: value, ...result }, c)
if (hookResult instanceof Response || hookResult instanceof Promise) { if (hookResult instanceof Response || hookResult instanceof Promise) {
return hookResult return hookResult
} }

View File

@ -88,7 +88,7 @@ describe('With Hook', () => {
'/post', '/post',
zValidator('json', schema, (result, c) => { zValidator('json', schema, (result, c) => {
if (!result.success) { if (!result.success) {
return c.text('Invalid!', 400) return c.text(`${result.data.id} is invalid!`, 400)
} }
const data = result.data const data = result.data
return c.text(`${data.id} is valid!`) return c.text(`${data.id} is valid!`)
@ -127,5 +127,6 @@ describe('With Hook', () => {
const res = await app.request(req) const res = await app.request(req)
expect(res).not.toBeNull() expect(res).not.toBeNull()
expect(res.status).toBe(400) expect(res.status).toBe(400)
expect(await res.text()).toBe('123 is invalid!')
}) })
}) })