validator.test.ts
This file
Path
src/validator/validator.test.ts
928 lines 路 20.9 KiB 路 TypeScript
Last changed by
fix(validator): use the cached content (#2234)Yusuke Wadabefore adoptione2f1d14
History of this fileTake 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('Cached contents', () => {176 const app = new Hono()177178 app.post(179 '/json',180 async (c, next) => {181 await c.req.json()182 await next()183 },184 validator('json', (value) => {185 return value186 }),187 async (c) => {188 const data = await c.req.json()189 return c.json(data, 200)190 }191 )192193 app.post(194 '/form',195 async (c, next) => {196 await c.req.formData()197 await next()198 },199 validator('form', (value) => {200 return value201 }),202 async (c) => {203 return c.json({ message: 'OK' }, 200)204 }205 )206207 it('Should return the cached JSON content', async () => {208 const res = await app.request('/json', {209 method: 'POST',210 body: JSON.stringify({ message: 'Hello' }),211 headers: {212 'Content-Type': 'application/json',213 },214 })215 expect(res.status).toBe(200)216 expect(await res.json()).toEqual({ message: 'Hello' })217 })218219 it('Should return the cached form content', async () => {220 const form = new FormData()221 form.append('message', 'Hello')222 const res = await app.request('/form', {223 method: 'POST',224 body: form,225 })226 expect(res.status).toBe(200)227 expect(await res.json()).toEqual({ message: 'OK' })228 })229})230231describe('Validator middleware with a custom validation function', () => {232 const app = new Hono()233234 const validationFunction: ValidationFunction<{ id: string }, { id: number }> = (v) => {235 return {236 id: Number(v.id),237 }238 }239240 const route = app.post('/post', validator('json', validationFunction), (c) => {241 const post = c.req.valid('json')242 type Expected = {243 id: number244 }245 type verify = Expect<Equal<Expected, typeof post>>246 return c.json({247 post,248 })249 })250251 type Expected = {252 '/post': {253 $post: {254 input: {255 json: {256 id: string257 }258 }259 output: {260 post: {261 id: number262 }263 }264 }265 }266 }267268 type Actual = ExtractSchema<typeof route>269 type verify2 = Expect<Equal<Expected, Actual>>270271 it('Should validate JSON with transformation and return 200 response', async () => {272 const res = await app.request('http://localhost/post', {273 method: 'POST',274 headers: {275 'Content-Type': 'application/json',276 },277 body: JSON.stringify({278 id: '123',279 }),280 })281 expect(res.status).toBe(200)282 expect(await res.json()).toEqual({283 post: {284 id: 123,285 },286 })287 })288})289290describe('Validator middleware with Zod validates JSON', () => {291 const app = new Hono()292293 const schema = z.object({294 id: z.number(),295 title: z.string(),296 })297298 const route = app.post('/post', zodValidator('json', schema), (c) => {299 const post = c.req.valid('json')300 type Expected = {301 id: number302 title: string303 }304 type verify = Expect<Equal<Expected, typeof post>>305 return c.json({306 post: post,307 })308 })309310 type Expected = {311 '/post': {312 $post: {313 input: {314 json: {315 id: number316 title: string317 }318 }319 output: {320 post: {321 id: number322 title: string323 }324 }325 }326 }327 }328329 type Actual = ExtractSchema<typeof route>330331 type verify2 = Expect<Equal<Expected, Actual>>332333 it('Should validate JSON and return 200 response', async () => {334 const res = await app.request('http://localhost/post', {335 method: 'POST',336 headers: {337 'Content-Type': 'application/json',338 },339 body: JSON.stringify({340 id: 123,341 title: 'Hello',342 }),343 })344 expect(res.status).toBe(200)345 expect(await res.json()).toEqual({346 post: {347 id: 123,348 title: 'Hello',349 },350 })351 })352353 it('Should validate JSON and return 400 response', async () => {354 const res = await app.request('http://localhost/post', {355 method: 'POST',356 headers: {357 'Content-Type': 'application/json',358 },359 body: JSON.stringify({360 id: '123',361 title: 'Hello',362 }),363 })364 expect(res.status).toBe(400)365 expect(await res.text()).toBe('Invalid!')366 })367})368369describe('Validator middleware with Zod validates Form data', () => {370 const app = new Hono()371372 const schema = z.object({373 id: z.string(),374 title: z.string(),375 })376 app.post('/post', zodValidator('form', schema), (c) => {377 const post = c.req.valid('form')378 return c.json({379 post: post,380 })381 })382383 it('Should validate Form data and return 200 response', async () => {384 const form = new FormData()385 form.append('id', '123')386 form.append('title', 'Hello')387 const res = await app.request('http://localhost/post', {388 method: 'POST',389 body: form,390 })391 expect(res.status).toBe(200)392 expect(await res.json()).toEqual({393 post: {394 id: '123',395 title: 'Hello',396 },397 })398 })399400 it('Should validate Form data and return 400 response', async () => {401 const res = await app.request('http://localhost/post', {402 method: 'POST',403 })404 expect(res.status).toBe(400)405 expect(await res.text()).toBe('Invalid!')406 })407})408409describe('Validator middleware with Zod validates query params', () => {410 const app = new Hono()411412 const schema = z.object({413 page: z414 .string()415 .refine((v) => {416 return !isNaN(Number(v))417 })418 .transform((v) => {419 return Number(v)420 }),421 tag: z.array(z.string()),422 })423424 app.get('/search', zodValidator('query', schema), (c) => {425 const res = c.req.valid('query')426 return c.json({427 page: res.page,428 tags: res.tag,429 })430 })431432 it('Should validate query params and return 200 response', async () => {433 const res = await app.request('http://localhost/search?page=123&tag=a&tag=b')434 expect(res.status).toBe(200)435 expect(await res.json()).toEqual({436 page: 123,437 tags: ['a', 'b'],438 })439 })440441 it('Should validate query params and return 400 response', async () => {442 const res = await app.request('http://localhost/search?page=onetwothree')443 expect(res.status).toBe(400)444 expect(await res.text()).toBe('Invalid!')445 })446})447448describe('Validator middleware with Zod validates param', () => {449 const app = new Hono()450451 const schema = z.object({452 id: z453 .string()454 .regex(/^[0-9]+$/)455 .transform((v) => {456 return Number(v)457 }),458 title: z.string(),459 })460 app.get('/users/:id/books/:title', zodValidator('param', schema), (c) => {461 const param = c.req.valid('param')462 return c.json({463 param: param,464 })465 })466467 it('Should validate Form data and return 200 response', async () => {468 const res = await app.request('http://localhost/users/123/books/Hello')469 expect(res.status).toBe(200)470 expect(await res.json()).toEqual({471 param: {472 id: 123,473 title: 'Hello',474 },475 })476 })477478 it('Should validate Form data and return 400 response', async () => {479 const res = await app.request('http://localhost/users/0.123/books/Hello')480 expect(res.status).toBe(400)481 expect(await res.text()).toBe('Invalid!')482 })483})484485describe('Validator middleware with Zod validates header values', () => {486 const app = new Hono()487488 const schema = z.object({489 'x-request-id': z.string().uuid(),490 })491492 app.get('/ping', zodValidator('header', schema), (c) => {493 const data = c.req.valid('header')494 const xRequestId = data['x-request-id']495 return c.json({496 xRequestId,497 })498 })499500 it('Should validate header values and return 200 response', async () => {501 const res = await app.request('/ping', {502 headers: {503 'x-request-id': '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b',504 },505 })506 expect(res.status).toBe(200)507 expect(await res.json()).toEqual({508 xRequestId: '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b',509 })510 })511512 it('Should validate header values and return 400 response', async () => {513 const res = await app.request('http://localhost/ping', {514 headers: {515 'x-request-id': 'invalid-key',516 },517 })518 expect(res.status).toBe(400)519 expect(await res.text()).toBe('Invalid!')520 })521})522523describe('Validator middleware with Zod validates cookies', () => {524 const app = new Hono()525526 const schema = z.object({527 debug: z.enum(['0', '1']),528 })529530 app.get('/api/user', zodValidator('cookie', schema), (c) => {531 const { debug } = c.req.valid('cookie')532 return c.json({533 debug,534 })535 })536537 it('Should validate cookies and return 200 response', async () => {538 const res = await app.request('/api/user', {539 headers: {540 Cookie: 'debug=0',541 },542 })543 expect(res.status).toBe(200)544 expect(await res.json()).toEqual({545 debug: '0',546 })547 })548549 it('Should validate cookies and return 400 response', async () => {550 const res = await app.request('/api/user', {551 headers: {552 Cookie: 'debug=true',553 },554 })555 expect(res.status).toBe(400)556 expect(await res.text()).toBe('Invalid!')557 })558})559560describe('Validator middleware with Zod multiple validators', () => {561 const app = new Hono<{ Variables: { id: number } }>()562 const route = app.post(563 '/posts',564 zodValidator(565 'query',566 z.object({567 page: z568 .string()569 .refine((v) => {570 return !isNaN(Number(v))571 })572 .transform((v) => {573 return Number(v)574 }),575 })576 ),577 zodValidator(578 'form',579 z.object({580 title: z.string(),581 })582 ),583 (c) => {584 const id = c.get('id')585 type verify = Expect<Equal<number, typeof id>>586 const formValidatedData = c.req.valid('form')587 type verify2 = Expect<Equal<{ title: string }, typeof formValidatedData>>588 const { page } = c.req.valid('query')589 const { title } = c.req.valid('form')590 return c.json({ page, title })591 }592 )593594 type Actual = ExtractSchema<typeof route>595596 type Expected = {597 '/posts': {598 $post: {599 input: {600 query: {601 page: string602 }603 } & {604 form: {605 title: string606 }607 }608 output: {609 page: number610 title: string611 }612 }613 }614 }615616 type verify = Expect<Equal<Expected, Actual>>617618 it('Should validate both query param and form data and return 200 response', async () => {619 const form = new FormData()620 form.append('title', 'Hello')621 const res = await app.request('http://localhost/posts?page=2', {622 method: 'POST',623 body: form,624 })625 expect(res.status).toBe(200)626 expect(await res.json()).toEqual({627 page: 2,628 title: 'Hello',629 })630 })631632 it('Should validate both query param and form data and return 400 response', async () => {633 const res = await app.request('http://localhost/posts?page=2', {634 method: 'POST',635 })636 expect(res.status).toBe(400)637 expect(await res.text()).toBe('Invalid!')638 })639})640641it('With path parameters', () => {642 const app = new Hono()643644 const route = app.put(645 '/posts/:id',646 validator('form', () => {647 return {648 title: 'Foo',649 }650 }),651 (c) => {652 return c.text('Valid!')653 }654 )655656 type Expected = {657 '/posts/:id': {658 $put: {659 input: {660 form: {661 title: string | File662 }663 } & {664 param: {665 id: string666 }667 }668 output: {}669 }670 }671 }672673 type Actual = ExtractSchema<typeof route>674 type verify = Expect<Equal<Expected, Actual>>675})676677it('`on`', () => {678 const app = new Hono()679680 const route = app.on(681 'PURGE',682 '/purge',683 validator('form', () => {684 return {685 tag: 'foo',686 }687 }),688 validator('query', () => {689 return {690 q: 'bar',691 }692 }),693 (c) => {694 return c.json({695 success: true,696 })697 }698 )699700 type Expected = {701 '/purge': {702 $purge: {703 input: {704 form: {705 tag: string | File706 }707 } & {708 query: {709 q: string | string[]710 }711 }712 output: {713 success: boolean714 }715 }716 }717 }718719 type Actual = ExtractSchema<typeof route>720 type verify = Expect<Equal<Expected, Actual>>721})722723it('`app.on`', () => {724 const app = new Hono()725726 const route = app727 .get(728 '/posts',729 validator('query', () => {730 return {731 page: '2',732 }733 }),734 (c) => {735 return c.json({736 posts: [737 {738 title: 'foo',739 },740 ],741 })742 }743 )744 .post(745 validator('json', () => {746 return {747 title: 'Hello',748 }749 }),750 validator('query', () => {751 return {752 title: 'Hello',753 }754 }),755 (c) => {756 return c.json({757 success: true,758 })759 }760 )761762 type Actual = ExtractSchema<typeof route>763 //type verify = Expect<Equal<Expected, Actual>>764})765766describe('Clone Request object', () => {767 describe('json', () => {768 const app = new Hono()769 app.post(770 '/',771 validator('json', () => {772 return {773 foo: 'bar',774 }775 }),776 async (c) => {777 // `c.req.json()` should not throw the error778 await c.req.json()779 // `c.req.text()` should not throw the error780 await c.req.text()781 // `c.req.arrayBuffer()` should not throw the error782 await c.req.arrayBuffer()783 // `c.req.blob()` should not throw the error784 await c.req.blob()785 return c.text('foo')786 }787 )788789 it('Should not throw the error with c.req.json()', async () => {790 const req = new Request('http://localhost', {791 method: 'POST',792 headers: {793 'Content-Type': 'application/json',794 },795 body: JSON.stringify({ foo: 'bar' }),796 })797 const res = await app.request(req)798 expect(res.status).toBe(200)799 })800 })801802 describe('form', () => {803 const app = new Hono()804 app.post(805 '/',806 validator('form', () => {807 return {808 foo: 'bar',809 }810 }),811 async (c) => {812 // `c.req.parseBody()` should not throw the error813 await c.req.parseBody()814 // `c.req.text()` should not throw the error815 await c.req.text()816 // `c.req.arrayBuffer()` should not throw the error817 await c.req.arrayBuffer()818 // `c.req.blob()` should not throw the error819 await c.req.blob()820 return c.text('foo')821 }822 )823824 it('Should not throw the error with c.req.parseBody()', async () => {825 const body = new FormData()826 body.append('foo', 'bar')827 const req = new Request('http://localhost', {828 method: 'POST',829 body: body,830 })831 const res = await app.request(req)832 expect(res.status).toBe(200)833 })834 })835})836837describe('Async validator function', () => {838 const app = new Hono()839840 app.get(841 '/posts',842 validator('query', async () => {843 return {844 page: '1',845 }846 }),847 (c) => {848 const { page } = c.req.valid('query')849 return c.json({ page })850 }851 )852853 it('Should get the values from the async function', async () => {854 const res = await app.request('/posts')855 expect(res.status).toBe(200)856 expect(await res.json()).toEqual({857 page: '1',858 })859 })860})861862describe('Validator with using Zod directly', () => {863 it('Should exclude Response & TypedResponse type', () => {864 const testSchema = z.object({865 name: z.string(),866 age: z.number(),867 type: z.enum(['a']),868 })869 const app = new Hono()870871 app.post(872 '/posts',873 validator('json', (value, c) => {874 const parsed = testSchema.safeParse(value)875 if (!parsed.success) {876 return c.json({ foo: 'bar' }, 401)877 }878 return parsed.data879 }),880 (c) => {881 const data = c.req.valid('json')882 expectTypeOf(data.name).toEqualTypeOf<string>()883 return c.json(884 {885 message: 'Created!',886 },887 201888 )889 }890 )891 })892})893894describe('Transform', () => {895 it('Should be number when the type is transformed', () => {896 const route = new Hono().get(897 '/',898 validator('query', async () => {899 return {900 page: 1,901 }902 }),903 (c) => {904 const { page } = c.req.valid('query')905 expectTypeOf(page).toEqualTypeOf<number>()906 return c.json({ page })907 }908 )909910 type Expected = {911 '/': {912 $get: {913 input: {914 query: {915 page: string | string[]916 }917 }918 output: {919 page: number920 }921 }922 }923 }924925 type Actual = ExtractSchema<typeof route>926 type verify = Expect<Equal<Expected, Actual>>927 })928})