Skip to content
Myr

validator.test.ts

This file

Path

src/validator/validator.test.ts

872 lines 路 19.7 KiB 路 TypeScript

Last changed by

Merge pull request #2167 from honojs/v4Yusuke Wadabefore adoption2c44ad7

History of this file

Take it

1/* eslint-disable @typescript-eslint/no-unused-vars */2import type { ZodSchema } from 'zod'3import { z } from 'zod'4import { Hono } from '../hono'5import { HTTPException } from '../http-exception'6import type { ErrorHandler, ExtractSchema, MiddlewareHandler, ValidationTargets } from '../types'7import type { Equal, Expect } from '../utils/types'8import type { ValidationFunction } from './validator'9import { validator } from './validator'1011// Reference implementation for only testing12const zodValidator = <13  T extends ZodSchema,14  E extends {},15  P extends string,16  Target extends keyof ValidationTargets17>(18  target: Target,19  schema: T20): MiddlewareHandler<21  E,22  P,23  { in: { [K in Target]: z.input<T> }; out: { [K in Target]: z.output<T> } }24> =>25  validator(target, (value, c) => {26    const result = schema.safeParse(value)27    if (!result.success) {28      return c.text('Invalid!', 400)29    }30    const data = result.data as z.output<T>31    return data32  })3334describe('Validator middleware', () => {35  const app = new Hono()3637  const route = app.get(38    '/search',39    async (_c, next) => {40      await next()41    },42    validator('query', (value, c) => {43      type verify = Expect<Equal<Record<string, string | string[]>, typeof value>>44      if (!value) {45        return c.text('Invalid!', 400)46      }47    }),48    (c) => {49      return c.text('Valid!')50    }51  )5253  type Expected = {54    '/search': {55      $get: {56        input: {57          query: undefined58        }59        output: {}60      }61    }62  }6364  type Actual = ExtractSchema<typeof route>6566  type verify = Expect<Equal<Expected, Actual>>6768  it('Should return 200 response', async () => {69    const res = await app.request('http://localhost/search?q=foo')70    expect(res.status).toBe(200)71  })7273  it('Should return 400 response', async () => {74    const res = await app.request('http://localhost/search')75    expect(res.status).toBe(200)76  })77})7879const onErrorHandler: ErrorHandler = (e, c) => {80  if (e instanceof HTTPException) {81    return c.json({ message: e.message, success: false }, e.status)82  }83  return c.json({ message: e.message }, 500)84}8586describe('Malformed JSON', () => {87  const app = new Hono()88  app.post(89    '/post',90    validator('json', (value, c) => {}),91    (c) => {92      return c.text('Valid!')93    }94  )95  app.onError(onErrorHandler)9697  it('Should return 400 response', async () => {98    const res = await app.request('http://localhost/post', {99      method: 'POST',100    })101    expect(res.status).toBe(400)102  })103104  it('Should return 400 response, for request with wrong Content-Type header', async () => {105    const res = await app.request('http://localhost/post', {106      method: 'POST',107      headers: {108        'Content-Type': 'text/plain;charset=utf-8',109      },110      body: JSON.stringify({111        any: 'thing',112      }),113    })114    expect(res.status).toBe(400)115  })116117  it('Should return 400 response, if Content-Type header does not start with application/json', async () => {118    const res = await app.request('http://localhost/post', {119      method: 'POST',120      headers: {121        'Content-Type': 'Xapplication/json',122      },123      body: JSON.stringify({124        any: 'thing',125      }),126    })127    expect(res.status).toBe(400)128    expect(await res.json()).toEqual({129      success: false,130      message: 'Invalid HTTP header: Content-Type=Xapplication/json',131    })132  })133})134135describe('Malformed FormData request', () => {136  const app = new Hono()137  app.post(138    '/post',139    validator('form', (value, c) => ({})),140    (c) => {141      return c.text('Valid!')142    }143  )144  app.onError(onErrorHandler)145146  it('Should return 400 response, for unsupported content type header', async () => {147    const res = await app.request('http://localhost/post', {148      method: 'POST',149      body: 'hi',150    })151    expect(res.status).toBe(400)152    const data = await res.json()153    expect(data['success']).toBe(false)154    expect(data['message']).toMatch(155      /Malformed FormData request. \_*Response.formData: Could not parse content as FormData./156    )157  })158159  it('Should return 400 response, for malformed content type header', async () => {160    const res = await app.request('http://localhost/post', {161      method: 'POST',162      body: 'hi',163      headers: {164        'content-type': 'multipart/form-data',165      },166    })167    expect(res.status).toBe(400)168    expect(await res.json()).toEqual({169      success: false,170      message: 'Malformed FormData request. Error: Multipart: Boundary not found',171    })172  })173})174175describe('Validator middleware with a custom validation function', () => {176  const app = new Hono()177178  const validationFunction: ValidationFunction<{ id: string }, { id: number }> = (v) => {179    return {180      id: Number(v.id),181    }182  }183184  const route = app.post('/post', validator('json', validationFunction), (c) => {185    const post = c.req.valid('json')186    type Expected = {187      id: number188    }189    type verify = Expect<Equal<Expected, typeof post>>190    return c.json({191      post,192    })193  })194195  type Expected = {196    '/post': {197      $post: {198        input: {199          json: {200            id: string201          }202        }203        output: {204          post: {205            id: number206          }207        }208      }209    }210  }211212  type Actual = ExtractSchema<typeof route>213  type verify2 = Expect<Equal<Expected, Actual>>214215  it('Should validate JSON with transformation and return 200 response', async () => {216    const res = await app.request('http://localhost/post', {217      method: 'POST',218      headers: {219        'Content-Type': 'application/json',220      },221      body: JSON.stringify({222        id: '123',223      }),224    })225    expect(res.status).toBe(200)226    expect(await res.json()).toEqual({227      post: {228        id: 123,229      },230    })231  })232})233234describe('Validator middleware with Zod validates JSON', () => {235  const app = new Hono()236237  const schema = z.object({238    id: z.number(),239    title: z.string(),240  })241242  const route = app.post('/post', zodValidator('json', schema), (c) => {243    const post = c.req.valid('json')244    type Expected = {245      id: number246      title: string247    }248    type verify = Expect<Equal<Expected, typeof post>>249    return c.json({250      post: post,251    })252  })253254  type Expected = {255    '/post': {256      $post: {257        input: {258          json: {259            id: number260            title: string261          }262        }263        output: {264          post: {265            id: number266            title: string267          }268        }269      }270    }271  }272273  type Actual = ExtractSchema<typeof route>274275  type verify2 = Expect<Equal<Expected, Actual>>276277  it('Should validate JSON and return 200 response', async () => {278    const res = await app.request('http://localhost/post', {279      method: 'POST',280      headers: {281        'Content-Type': 'application/json',282      },283      body: JSON.stringify({284        id: 123,285        title: 'Hello',286      }),287    })288    expect(res.status).toBe(200)289    expect(await res.json()).toEqual({290      post: {291        id: 123,292        title: 'Hello',293      },294    })295  })296297  it('Should validate JSON and return 400 response', async () => {298    const res = await app.request('http://localhost/post', {299      method: 'POST',300      headers: {301        'Content-Type': 'application/json',302      },303      body: JSON.stringify({304        id: '123',305        title: 'Hello',306      }),307    })308    expect(res.status).toBe(400)309    expect(await res.text()).toBe('Invalid!')310  })311})312313describe('Validator middleware with Zod validates Form data', () => {314  const app = new Hono()315316  const schema = z.object({317    id: z.string(),318    title: z.string(),319  })320  app.post('/post', zodValidator('form', schema), (c) => {321    const post = c.req.valid('form')322    return c.json({323      post: post,324    })325  })326327  it('Should validate Form data and return 200 response', async () => {328    const form = new FormData()329    form.append('id', '123')330    form.append('title', 'Hello')331    const res = await app.request('http://localhost/post', {332      method: 'POST',333      body: form,334    })335    expect(res.status).toBe(200)336    expect(await res.json()).toEqual({337      post: {338        id: '123',339        title: 'Hello',340      },341    })342  })343344  it('Should validate Form data and return 400 response', async () => {345    const res = await app.request('http://localhost/post', {346      method: 'POST',347    })348    expect(res.status).toBe(400)349    expect(await res.text()).toBe('Invalid!')350  })351})352353describe('Validator middleware with Zod validates query params', () => {354  const app = new Hono()355356  const schema = z.object({357    page: z358      .string()359      .refine((v) => {360        return !isNaN(Number(v))361      })362      .transform((v) => {363        return Number(v)364      }),365    tag: z.array(z.string()),366  })367368  app.get('/search', zodValidator('query', schema), (c) => {369    const res = c.req.valid('query')370    return c.json({371      page: res.page,372      tags: res.tag,373    })374  })375376  it('Should validate query params and return 200 response', async () => {377    const res = await app.request('http://localhost/search?page=123&tag=a&tag=b')378    expect(res.status).toBe(200)379    expect(await res.json()).toEqual({380      page: 123,381      tags: ['a', 'b'],382    })383  })384385  it('Should validate query params and return 400 response', async () => {386    const res = await app.request('http://localhost/search?page=onetwothree')387    expect(res.status).toBe(400)388    expect(await res.text()).toBe('Invalid!')389  })390})391392describe('Validator middleware with Zod validates param', () => {393  const app = new Hono()394395  const schema = z.object({396    id: z397      .string()398      .regex(/^[0-9]+$/)399      .transform((v) => {400        return Number(v)401      }),402    title: z.string(),403  })404  app.get('/users/:id/books/:title', zodValidator('param', schema), (c) => {405    const param = c.req.valid('param')406    return c.json({407      param: param,408    })409  })410411  it('Should validate Form data and return 200 response', async () => {412    const res = await app.request('http://localhost/users/123/books/Hello')413    expect(res.status).toBe(200)414    expect(await res.json()).toEqual({415      param: {416        id: 123,417        title: 'Hello',418      },419    })420  })421422  it('Should validate Form data and return 400 response', async () => {423    const res = await app.request('http://localhost/users/0.123/books/Hello')424    expect(res.status).toBe(400)425    expect(await res.text()).toBe('Invalid!')426  })427})428429describe('Validator middleware with Zod validates header values', () => {430  const app = new Hono()431432  const schema = z.object({433    'x-request-id': z.string().uuid(),434  })435436  app.get('/ping', zodValidator('header', schema), (c) => {437    const data = c.req.valid('header')438    const xRequestId = data['x-request-id']439    return c.json({440      xRequestId,441    })442  })443444  it('Should validate header values and return 200 response', async () => {445    const res = await app.request('/ping', {446      headers: {447        'x-request-id': '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b',448      },449    })450    expect(res.status).toBe(200)451    expect(await res.json()).toEqual({452      xRequestId: '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b',453    })454  })455456  it('Should validate header values and return 400 response', async () => {457    const res = await app.request('http://localhost/ping', {458      headers: {459        'x-request-id': 'invalid-key',460      },461    })462    expect(res.status).toBe(400)463    expect(await res.text()).toBe('Invalid!')464  })465})466467describe('Validator middleware with Zod validates cookies', () => {468  const app = new Hono()469470  const schema = z.object({471    debug: z.enum(['0', '1']),472  })473474  app.get('/api/user', zodValidator('cookie', schema), (c) => {475    const { debug } = c.req.valid('cookie')476    return c.json({477      debug,478    })479  })480481  it('Should validate cookies and return 200 response', async () => {482    const res = await app.request('/api/user', {483      headers: {484        Cookie: 'debug=0',485      },486    })487    expect(res.status).toBe(200)488    expect(await res.json()).toEqual({489      debug: '0',490    })491  })492493  it('Should validate cookies and return 400 response', async () => {494    const res = await app.request('/api/user', {495      headers: {496        Cookie: 'debug=true',497      },498    })499    expect(res.status).toBe(400)500    expect(await res.text()).toBe('Invalid!')501  })502})503504describe('Validator middleware with Zod multiple validators', () => {505  const app = new Hono<{ Variables: { id: number } }>()506  const route = app.post(507    '/posts',508    zodValidator(509      'query',510      z.object({511        page: z512          .string()513          .refine((v) => {514            return !isNaN(Number(v))515          })516          .transform((v) => {517            return Number(v)518          }),519      })520    ),521    zodValidator(522      'form',523      z.object({524        title: z.string(),525      })526    ),527    (c) => {528      const id = c.get('id')529      type verify = Expect<Equal<number, typeof id>>530      const formValidatedData = c.req.valid('form')531      type verify2 = Expect<Equal<{ title: string }, typeof formValidatedData>>532      const { page } = c.req.valid('query')533      const { title } = c.req.valid('form')534      return c.json({ page, title })535    }536  )537538  type Actual = ExtractSchema<typeof route>539540  type Expected = {541    '/posts': {542      $post: {543        input: {544          query: {545            page: string546          }547        } & {548          form: {549            title: string550          }551        }552        output: {553          page: number554          title: string555        }556      }557    }558  }559560  type verify = Expect<Equal<Expected, Actual>>561562  it('Should validate both query param and form data and return 200 response', async () => {563    const form = new FormData()564    form.append('title', 'Hello')565    const res = await app.request('http://localhost/posts?page=2', {566      method: 'POST',567      body: form,568    })569    expect(res.status).toBe(200)570    expect(await res.json()).toEqual({571      page: 2,572      title: 'Hello',573    })574  })575576  it('Should validate both query param and form data and return 400 response', async () => {577    const res = await app.request('http://localhost/posts?page=2', {578      method: 'POST',579    })580    expect(res.status).toBe(400)581    expect(await res.text()).toBe('Invalid!')582  })583})584585it('With path parameters', () => {586  const app = new Hono()587588  const route = app.put(589    '/posts/:id',590    validator('form', () => {591      return {592        title: 'Foo',593      }594    }),595    (c) => {596      return c.text('Valid!')597    }598  )599600  type Expected = {601    '/posts/:id': {602      $put: {603        input: {604          form: {605            title: string | File606          }607        } & {608          param: {609            id: string610          }611        }612        output: {}613      }614    }615  }616617  type Actual = ExtractSchema<typeof route>618  type verify = Expect<Equal<Expected, Actual>>619})620621it('`on`', () => {622  const app = new Hono()623624  const route = app.on(625    'PURGE',626    '/purge',627    validator('form', () => {628      return {629        tag: 'foo',630      }631    }),632    validator('query', () => {633      return {634        q: 'bar',635      }636    }),637    (c) => {638      return c.json({639        success: true,640      })641    }642  )643644  type Expected = {645    '/purge': {646      $purge: {647        input: {648          form: {649            tag: string | File650          }651        } & {652          query: {653            q: string | string[]654          }655        }656        output: {657          success: boolean658        }659      }660    }661  }662663  type Actual = ExtractSchema<typeof route>664  type verify = Expect<Equal<Expected, Actual>>665})666667it('`app.on`', () => {668  const app = new Hono()669670  const route = app671    .get(672      '/posts',673      validator('query', () => {674        return {675          page: '2',676        }677      }),678      (c) => {679        return c.json({680          posts: [681            {682              title: 'foo',683            },684          ],685        })686      }687    )688    .post(689      validator('json', () => {690        return {691          title: 'Hello',692        }693      }),694      validator('query', () => {695        return {696          title: 'Hello',697        }698      }),699      (c) => {700        return c.json({701          success: true,702        })703      }704    )705706  type Actual = ExtractSchema<typeof route>707  //type verify = Expect<Equal<Expected, Actual>>708})709710describe('Clone Request object', () => {711  describe('json', () => {712    const app = new Hono()713    app.post(714      '/',715      validator('json', () => {716        return {717          foo: 'bar',718        }719      }),720      async (c) => {721        // `c.req.json()` should not throw the error722        await c.req.json()723        // `c.req.text()` should not throw the error724        await c.req.text()725        // `c.req.arrayBuffer()` should not throw the error726        await c.req.arrayBuffer()727        // `c.req.blob()` should not throw the error728        await c.req.blob()729        return c.text('foo')730      }731    )732733    it('Should not throw the error with c.req.json()', async () => {734      const req = new Request('http://localhost', {735        method: 'POST',736        headers: {737          'Content-Type': 'application/json',738        },739        body: JSON.stringify({ foo: 'bar' }),740      })741      const res = await app.request(req)742      expect(res.status).toBe(200)743    })744  })745746  describe('form', () => {747    const app = new Hono()748    app.post(749      '/',750      validator('form', () => {751        return {752          foo: 'bar',753        }754      }),755      async (c) => {756        // `c.req.parseBody()` should not throw the error757        await c.req.parseBody()758        // `c.req.text()` should not throw the error759        await c.req.text()760        // `c.req.arrayBuffer()` should not throw the error761        await c.req.arrayBuffer()762        // `c.req.blob()` should not throw the error763        await c.req.blob()764        return c.text('foo')765      }766    )767768    it('Should not throw the error with c.req.parseBody()', async () => {769      const body = new FormData()770      body.append('foo', 'bar')771      const req = new Request('http://localhost', {772        method: 'POST',773        body: body,774      })775      const res = await app.request(req)776      expect(res.status).toBe(200)777    })778  })779})780781describe('Async validator function', () => {782  const app = new Hono()783784  app.get(785    '/posts',786    validator('query', async () => {787      return {788        page: '1',789      }790    }),791    (c) => {792      const { page } = c.req.valid('query')793      return c.json({ page })794    }795  )796797  it('Should get the values from the async function', async () => {798    const res = await app.request('/posts')799    expect(res.status).toBe(200)800    expect(await res.json()).toEqual({801      page: '1',802    })803  })804})805806describe('Validator with using Zod directly', () => {807  it('Should exclude Response & TypedResponse type', () => {808    const testSchema = z.object({809      name: z.string(),810      age: z.number(),811      type: z.enum(['a']),812    })813    const app = new Hono()814815    app.post(816      '/posts',817      validator('json', (value, c) => {818        const parsed = testSchema.safeParse(value)819        if (!parsed.success) {820          return c.json({ foo: 'bar' }, 401)821        }822        return parsed.data823      }),824      (c) => {825        const data = c.req.valid('json')826        expectTypeOf(data.name).toEqualTypeOf<string>()827        return c.json(828          {829            message: 'Created!',830          },831          201832        )833      }834    )835  })836})837838describe('Transform', () => {839  it('Should be number when the type is transformed', () => {840    const route = new Hono().get(841      '/',842      validator('query', async () => {843        return {844          page: 1,845        }846      }),847      (c) => {848        const { page } = c.req.valid('query')849        expectTypeOf(page).toEqualTypeOf<number>()850        return c.json({ page })851      }852    )853854    type Expected = {855      '/': {856        $get: {857          input: {858            query: {859              page: string | string[]860            }861          }862          output: {863            page: number864          }865        }866      }867    }868869    type Actual = ExtractSchema<typeof route>870    type verify = Expect<Equal<Expected, Actual>>871  })872})