Skip to content
Myr

fix(validator): exclude Response type for returned values from `c.req.valid()` (#1914)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* fix(validator): exclude Response type for returned values from `c.req.valid()` * denoify

authored by Yusuke Wada · committed by GitHub · parent 2d8d59f · Browse files · 3 files+44 added−6 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+44 added−6 removed

  • tests:+32 added−0 removed
  • other:+12 added−6 removed

3 files+44 added−6 removed

modified:deno_dist/validator/validator.ts+6 added-3 removed
modified:src/validator/validator.test.ts+32 added
820 unmodified lines
821 page: '1',822 })823 })824})825826describe('Validator with using Zod directly', () => {827 it('Should exclude Response & TypedResponse type', () => {828 const testSchema = z.object({829 name: z.string(),830 age: z.number(),831 type: z.enum(['a']),832 })833 const app = new Hono()834835 app.post(836 '/posts',837 validator('json', (value, c) => {838 const parsed = testSchema.safeParse(value)839 if (!parsed.success) {840 return c.json({ foo: 'bar' }, 401)841 }842 return parsed.data843 }),844 (c) => {845 const data = c.req.valid('json')846 expectTypeOf(data.name).toEqualTypeOf<string>()847 return c.json(848 {849 message: 'Created!',850 },851 201852 )853 }854 )855 })856})
modified:src/validator/validator.ts+6 added-3 removed
1import type { Context } from '../context'2import { getCookie } from '../helper/cookie'3import type { Env, ValidationTargets, MiddlewareHandler } from '../types'3import type { Env, ValidationTargets, MiddlewareHandler, TypedResponse } from '../types'4import type { BodyData } from '../utils/body'5import { bufferToFormData } from '../utils/buffer'67type ValidationTargetKeysWithBody = 'form' | 'json'
10 unmodified lines
18 value: InputType,19 c: Context<E, P>20) => OutputType | Response | Promise<OutputType> | Promise<Response>2122// eslint-disable-next-line @typescript-eslint/no-explicit-any23type ExcludeResponseType<T> = T extends Response & TypedResponse<any> ? never : T2425export const validator = <26 InputType,27 P extends string,28 M extends string,
1 unmodified line
30 OutputType = ValidationTargets[U],31 P2 extends string = P,32 V extends {33 in: { [K in U]: unknown extends InputType ? OutputType : InputType }31 out: { [K in U]: OutputType }34 out: { [K in U]: ExcludeResponseType<OutputType> }35 } = {36 in: { [K in U]: unknown extends InputType ? OutputType : InputType }34 out: { [K in U]: OutputType }37 out: { [K in U]: ExcludeResponseType<OutputType> }38 },39 // eslint-disable-next-line @typescript-eslint/no-explicit-any40 E extends Env = any41>(
105 unmodified lines