client.test.ts
This file
Path
src/client/client.test.ts
1,944 lines · 54.7 KiB · TypeScript
Last changed by
feat(client): add `PickResponseByStatusCode` type (#4791)Yusuke Wadabefore adoptiond1722e3
History of this fileTake it
The walk stopped after 200 commits: lines older than 0d12626 point at it.
chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 1–12why, one step back1/* eslint-disable @typescript-eslint/no-unused-vars */23/* eslint-disable @typescript-eslint/ban-ts-comment */4import { HttpResponse, http } from 'msw'5import { setupServer } from 'msw/node'6import { expectTypeOf, vi } from 'vitest'7import { upgradeWebSocket } from '../adapter/deno/websocket'8import { Hono } from '../hono'9import { parse } from '../utils/cookie'10import type { Equal, Expect, JSONValue, SimplifyDeepArray } from '../utils/types'11import { validator } from '../validator'12import { hc } from './client'Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
lines 13–17why, one step back13import type {14 ClientResponse,15 InferRequestType,16 InferResponseType,17 ApplyGlobalResponse,feat(client): add `PickResponseByStatusCode` type (#4791)Yusuke Wadabefore adoptiond1722e3
line 18why, one step back18 PickResponseByStatusCode,Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
line 19why, one step back19} from './types'chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
line 20why, one step back20fix(types): JSONParsed infer unknown values (#4405)Jonathan Hainesbefore adoptionf8c9b6e
lines 21–30why, one step back21class SafeBigInt {22 unsafe = BigInt(42)2324 toJSON() {25 return {26 value: '42n',27 }28 }29}30chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 31–69why, one step back31describe('Basic - JSON', () => {32 const app = new Hono()3334 const route = app35 .post(36 '/posts',37 validator('cookie', () => {38 return {} as {39 debug: string40 }41 }),42 validator('header', () => {43 return {} as {44 'x-message': string45 }46 }),47 validator('json', () => {48 return {} as {49 id: number50 title: string51 }52 }),53 (c) => {54 return c.json({55 success: true,56 message: 'dummy',57 requestContentType: 'dummy',58 requestHono: 'dummy',59 requestMessage: 'dummy',60 requestBody: {61 id: 123,62 title: 'dummy',63 },64 })65 }66 )67 .get('/hello-not-found', (c) => c.notFound())68 .get('/null', (c) => c.json(null))69 .get('/empty', (c) => c.json({}))fix(types): JSONParsed infer unknown values (#4405)Jonathan Hainesbefore adoptionf8c9b6e
lines 70–71why, one step back70 .get('/bigint', (c) => c.json({ value: BigInt(42) }))71 .get('/safe-bigint', (c) => c.json(new SafeBigInt()))chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 72–101why, one step back7273 type AppType = typeof route7475 const server = setupServer(76 http.post('http://localhost/posts', async ({ request }) => {77 const requestContentType = request.headers.get('content-type')78 const requestHono = request.headers.get('x-hono')79 const requestMessage = request.headers.get('x-message')80 const requestBody = await request.json()81 const payload = {82 message: 'Hello!',83 success: true,84 requestContentType,85 requestHono,86 requestMessage,87 requestBody,88 }89 return HttpResponse.json(payload)90 }),91 http.get('http://localhost/hello-not-found', () => {92 return HttpResponse.text(null, {93 status: 404,94 })95 }),96 http.get('http://localhost/null', () => {97 return HttpResponse.json(null)98 }),99 http.get('http://localhost/empty', () => {100 return HttpResponse.json({})101 }),fix(types): JSONParsed infer unknown values (#4405)Jonathan Hainesbefore adoptionf8c9b6e
lines 102–107why, one step back102 http.get('http://localhost/bigint', () => {103 return HttpResponse.json({ value: BigInt(42) })104 }),105 http.get('http://localhost/safe-bigint', () => {106 return HttpResponse.json(new SafeBigInt())107 }),chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 108–175why, one step back108 http.get('http://localhost/api/string', () => {109 return HttpResponse.json('a-string')110 }),111 http.get('http://localhost/api/number', async () => {112 return HttpResponse.json(37)113 }),114 http.get('http://localhost/api/boolean', async () => {115 return HttpResponse.json(true)116 }),117 http.get('http://localhost/api/generic', async () => {118 return HttpResponse.json(Math.random() > 0.5 ? Boolean(Math.random()) : Math.random())119 })120 )121122 beforeAll(() => server.listen())123 afterEach(() => server.resetHandlers())124 afterAll(() => server.close())125126 const payload = {127 id: 123,128 title: 'Hello! Hono!',129 }130131 const client = hc<AppType>('http://localhost', { headers: { 'x-hono': 'hono' } })132133 it('Should get 200 response', async () => {134 const res = await client.posts.$post(135 {136 json: payload,137 header: {138 'x-message': 'foobar',139 },140 cookie: {141 debug: 'true',142 },143 },144 {}145 )146147 expect(res.ok).toBe(true)148 const data = await res.json()149 expect(data.success).toBe(true)150 expect(data.message).toBe('Hello!')151 expect(data.requestContentType).toBe('application/json')152 expect(data.requestHono).toBe('hono')153 expect(data.requestMessage).toBe('foobar')154 expect(data.requestBody).toEqual(payload)155 })156157 it('Should get 404 response', async () => {158 const res = await client['hello-not-found'].$get()159 expect(res.status).toBe(404)160 })161162 it('Should get a `null` content', async () => {163 const client = hc<AppType>('http://localhost')164 const res = await client.null.$get()165 const data = await res.json()166 expectTypeOf(data).toMatchTypeOf<null>()167 expect(data).toBe(null)168 })169170 it('Should get a `{}` content', async () => {171 const client = hc<AppType>('http://localhost')172 const res = await client.empty.$get()173 const data = await res.json()174 expectTypeOf(data).toMatchTypeOf<{}>()175 expect(data).toStrictEqual({})fix(types): JSONParsed infer unknown values (#4405)Jonathan Hainesbefore adoptionf8c9b6e
lines 176–195why, one step back176 })177178 it('Should get a `{}` content', async () => {179 const client = hc<AppType>('http://localhost')180 const res = await client['safe-bigint'].$get()181 const data = await res.json()182 expectTypeOf(data).toMatchTypeOf<{ value: string }>()183 expect(data).toStrictEqual({ value: '42n' })184 })185186 it('Should get an error response', async () => {187 const client = hc<AppType>('http://localhost')188 const res = await client.bigint.$get()189 const data = await res.json()190 expectTypeOf(data).toMatchTypeOf<never>()191 expect(res.status).toBe(500)192 expect(data).toMatchObject({193 message: 'Do not know how to serialize a BigInt',194 name: 'TypeError',195 })chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 196–402why, one step back196 })197198 it('Should have correct types - primitives', async () => {199 const app = new Hono()200 const route = app201 .get('/api/string', (c) => c.json('a-string'))202 .get('/api/number', (c) => c.json(37))203 .get('/api/boolean', (c) => c.json(true))204 .get('/api/generic', (c) =>205 c.json(Math.random() > 0.5 ? Boolean(Math.random()) : Math.random())206 )207 type AppType = typeof route208 const client = hc<AppType>('http://localhost')209 const stringFetch = await client.api.string.$get()210 const stringRes = await stringFetch.json()211 const numberFetch = await client.api.number.$get()212 const numberRes = await numberFetch.json()213 const booleanFetch = await client.api.boolean.$get()214 const booleanRes = await booleanFetch.json()215 const genericFetch = await client.api.generic.$get()216 const genericRes = await genericFetch.json()217 type stringVerify = Expect<Equal<'a-string', typeof stringRes>>218 expect(stringRes).toBe('a-string')219 type numberVerify = Expect<Equal<37, typeof numberRes>>220 expect(numberRes).toBe(37)221 type booleanVerify = Expect<Equal<true, typeof booleanRes>>222 expect(booleanRes).toBe(true)223 type genericVerify = Expect<Equal<number | boolean, typeof genericRes>>224 expect(typeof genericRes === 'number' || typeof genericRes === 'boolean').toBe(true)225226 // using .text() on json endpoint should return string227 type textTest = Expect<Equal<Promise<string>, ReturnType<typeof genericFetch.text>>>228 })229})230231describe('Basic - query, queries, form, path params, header and cookie', () => {232 const app = new Hono()233234 const route = app235 .get(236 '/search',237 validator('query', () => {238 return {} as { q: string; tag: string[]; filter: string }239 }),240 (c) => {241 return c.json({242 q: 'fake',243 tag: ['fake'],244 filter: 'fake',245 })246 }247 )248 .put(249 '/posts/:id',250 validator('form', () => {251 return {252 title: 'Hello',253 }254 }),255 (c) => {256 const data = c.req.valid('form')257 return c.json(data)258 }259 )260 .get(261 '/header',262 validator('header', () => {263 return {264 'x-message-id': 'Hello',265 }266 }),267 (c) => {268 const data = c.req.valid('header')269 return c.json(data)270 }271 )272 .get(273 '/cookie',274 validator('cookie', () => {275 return {276 hello: 'world',277 }278 }),279 (c) => {280 const data = c.req.valid('cookie')281 return c.json(data)282 }283 )284285 const server = setupServer(286 http.get('http://localhost/api/search', ({ request }) => {287 const url = new URL(request.url)288 const query = url.searchParams.get('q')289 const tag = url.searchParams.getAll('tag')290 const filter = url.searchParams.get('filter')291 return HttpResponse.json({292 q: query,293 tag,294 filter,295 })296 }),297 http.get('http://localhost/api/posts', ({ request }) => {298 const url = new URL(request.url)299 const tags = url.searchParams.getAll('tags')300 return HttpResponse.json({301 tags: tags,302 })303 }),304 http.put('http://localhost/api/posts/123', async ({ request }) => {305 const buffer = await request.arrayBuffer()306 // @ts-ignore307 const string = String.fromCharCode.apply('', new Uint8Array(buffer))308 return HttpResponse.text(string)309 }),310 http.get('http://localhost/api/header', async ({ request }) => {311 const message = await request.headers.get('x-message-id')312 return HttpResponse.json({ 'x-message-id': message })313 }),314 http.get('http://localhost/api/cookie', async ({ request }) => {315 const obj = parse(request.headers.get('cookie') || '')316 const value = obj['hello']317 return HttpResponse.json({ hello: value })318 })319 )320321 beforeAll(() => server.listen())322 afterEach(() => server.resetHandlers())323 afterAll(() => server.close())324325 type AppType = typeof route326327 const client = hc<AppType>('http://localhost/api')328329 it('Should get 200 response - query', async () => {330 const res = await client.search.$get({331 query: {332 q: 'foobar',333 tag: ['a', 'b'],334 // @ts-expect-error335 filter: undefined,336 },337 })338339 expect(res.status).toBe(200)340 expect(await res.json()).toEqual({341 q: 'foobar',342 tag: ['a', 'b'],343 filter: null,344 })345 })346347 it('Should get 200 response - form, params', async () => {348 const res = await client.posts[':id'].$put({349 form: {350 title: 'Good Night',351 },352 param: {353 id: '123',354 },355 })356357 expect(res.status).toBe(200)358 expect(await res.text()).toMatch('Good Night')359 })360361 it('Should get 200 response - header', async () => {362 const header = {363 'x-message-id': 'Hello',364 }365 const res = await client.header.$get({366 header,367 })368369 expect(res.status).toBe(200)370 expect(await res.json()).toEqual(header)371 })372373 it('Should get 200 response - cookie', async () => {374 const cookie = {375 hello: 'world',376 }377 const res = await client.cookie.$get({378 cookie,379 })380381 expect(res.status).toBe(200)382 expect(await res.json()).toEqual(cookie)383 })384})385386describe('Basic - $url()', () => {387 const api = new Hono().get('/', (c) => c.text('API')).get('/posts/:id', (c) => c.text('Post'))388 const content = new Hono().get(389 '/search',390 validator('query', () => {391 return { page: '1', limit: '10' }392 }),393 (c) => c.text('Search')394 )395 const app = new Hono()396 .get('/', (c) => c.text('Index'))397 .route('/api', api)398 .route('/content', content)399400 it('Should return a correct url via $url().href', async () => {401 const client = hc<typeof app>('http://fake')402 expect(client.index.$url().href).toBe('http://fake/')fix(client): handle query parameters in `removeIndexString` (#4352)Yusuke Wadabefore adoption6b19b5e
lines 403–410why, one step back403 expect(404 client.index.$url({405 query: {406 page: '123',407 limit: '20',408 },409 }).href410 ).toBe('http://fake/?page=123&limit=20')chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 411–427why, one step back411 expect(client.api.$url().href).toBe('http://fake/api')412 expect(413 client.api.posts[':id'].$url({414 param: {415 id: '123',416 },417 }).href418 ).toBe('http://fake/api/posts/123')419 expect(420 client.content.search.$url({421 query: {422 page: '123',423 limit: '20',424 },425 }).href426 ).toBe('http://fake/content/search?page=123&limit=20')427 })Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
lines 428–459why, one step back428429 it.each(['http://fake', 'http://fake/', 'http://fake//', 'http://fake/api'])(430 'Should return a correct path via $path() regardless of %s',431 async (baseURL) => {432 const client = hc<typeof app>(baseURL)433 expect(client.index.$path()).toBe('/')434 expect(435 client.index.$path({436 query: {437 page: '123',438 limit: '20',439 },440 })441 ).toBe('/?page=123&limit=20')442 expect(client.api.$path()).toBe('/api')443 expect(444 client.api.posts[':id'].$path({445 param: {446 id: '123',447 },448 })449 ).toBe('/api/posts/123')450 expect(451 client.content.search.$path({452 query: {453 page: '123',454 limit: '20',455 },456 })457 ).toBe('/content/search?page=123&limit=20')458 }459 )chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 460–487why, one step back460})461462describe('Form - Multiple Values', () => {463 const server = setupServer(464 http.post('http://localhost/multiple-values', async ({ request }) => {465 const data = await request.formData()466 return HttpResponse.json(data.getAll('key'))467 })468 )469470 beforeAll(() => server.listen())471 afterEach(() => server.resetHandlers())472 afterAll(() => server.close())473474 const client = hc('http://localhost/')475476 it('Should get 200 response - query', async () => {477 // @ts-expect-error `client['multiple-values'].$post` is not typed478 const res = await client['multiple-values'].$post({479 form: {480 key: ['foo', 'bar'],481 },482 })483 expect(res.status).toBe(200)484 expect(await res.json()).toEqual(['foo', 'bar'])485 })486})487fix(client): skip undefined values in form data serialization (#4732)Aiden Liubefore adoption67ac19a
lines 488–523why, one step back488describe('Form - Undefined Values', () => {489 const server = setupServer(490 http.post('http://localhost/form-undefined', async ({ request }) => {491 const data = await request.formData()492 return HttpResponse.json({493 keys: [...data.keys()],494 title: data.get('title'),495 optional: data.get('optional'),496 })497 })498 )499500 beforeAll(() => server.listen())501 afterEach(() => server.resetHandlers())502 afterAll(() => server.close())503504 const client = hc('http://localhost/')505506 it('Should skip undefined values in form data', async () => {507 // @ts-expect-error `client['form-undefined'].$post` is not typed508 const res = await client['form-undefined'].$post({509 form: {510 title: 'Hello',511 optional: undefined,512 },513 })514 expect(res.status).toBe(200)515 const json = await res.json()516 expect(json).toEqual({517 keys: ['title'],518 title: 'Hello',519 optional: null,520 })521 })522})523chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 524–609why, one step back524describe('Infer the response/request type', () => {525 const app = new Hono()526 const route = app.get(527 '/',528 validator('query', () => {529 return {530 name: 'dummy',531 age: 'dummy',532 }533 }),534 validator('header', () => {535 return {536 'x-request-id': 'dummy',537 }538 }),539 validator('cookie', () => {540 return {541 name: 'dummy',542 }543 }),544 (c) =>545 c.json({546 id: 123,547 title: 'Morning!',548 })549 )550551 type AppType = typeof route552553 it('Should infer response type the type correctly', () => {554 const client = hc<AppType>('/')555 const req = client.index.$get556557 type Actual = InferResponseType<typeof req>558 type Expected = {559 id: number560 title: string561 }562 type verify = Expect<Equal<Expected, Actual>>563 })564565 it('Should infer request type the type correctly', () => {566 const client = hc<AppType>('/')567 const req = client.index.$get568569 type Actual = InferRequestType<typeof req>570 type Expected = {571 age: string | string[]572 name: string | string[]573 }574 type verify = Expect<Equal<Expected, Actual['query']>>575 })576577 it('Should infer request header type the type correctly', () => {578 const client = hc<AppType>('/')579 const req = client.index.$get580 type c = typeof req581582 type Actual = InferRequestType<c>583 type Expected = {584 'x-request-id': string585 }586 type verify = Expect<Equal<Expected, Actual['header']>>587 })588589 it('Should infer request cookie type the type correctly', () => {590 const client = hc<AppType>('/')591 const req = client.index.$get592 type c = typeof req593594 type Actual = InferRequestType<c>595 type Expected = {596 name: string597 }598 type verify = Expect<Equal<Expected, Actual['cookie']>>599 })600601 describe('Without input', () => {602 const route = app.get('/', (c) => c.json({ ok: true }))603 type AppType = typeof route604605 it('Should infer response type the type correctly', () => {606 const client = hc<AppType>('/')607 const req = client.index.$get608609 type Actual = InferResponseType<typeof req>chore: update `typescript` to `5.9.2` (#4362)Yusuke Wadabefore adoption3e5a6e8
line 610why, one step back610 type Expected = { ok: true }chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 611–672why, one step back611 type verify = Expect<Equal<Expected, Actual>>612 })613614 it('Should infer request type the type correctly', () => {615 const client = hc<AppType>('/')616 const req = client.index.$get617618 type Actual = InferRequestType<typeof req>619 type Expected = {}620 type verify = Expect<Equal<Expected, Actual>>621 })622 })623})624625describe('Merge path with `app.route()`', () => {626 const server = setupServer(627 http.get('http://localhost/api/search', async () => {628 return HttpResponse.json({629 ok: true,630 })631 }),632 http.get('http://localhost/api/searchArray', async () => {633 return HttpResponse.json([634 {635 ok: true,636 },637 ])638 }),639 http.get('http://localhost/api/foo', async () => {640 return HttpResponse.json({641 ok: true,642 })643 }),644 http.post('http://localhost/api/bar', async () => {645 return HttpResponse.json({646 ok: true,647 })648 }),649 http.get('http://localhost/v1/book', async () => {650 return HttpResponse.json({651 ok: true,652 })653 })654 )655656 beforeAll(() => server.listen())657 afterEach(() => server.resetHandlers())658 afterAll(() => server.close())659660 type Env = {661 Bindings: {662 TOKEN: string663 }664 }665666 it('Should have correct types', async () => {667 const api = new Hono<Env>().get('/search', (c) => c.json({ ok: true }))668 const app = new Hono<Env>().route('/api', api)669 type AppType = typeof app670 const client = hc<AppType>('http://localhost')671 const res = await client.api.search.$get()672 const data = await res.json()chore: update `typescript` to `5.9.2` (#4362)Yusuke Wadabefore adoption3e5a6e8
line 673why, one step back673 type verify = Expect<Equal<true, typeof data.ok>>chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 674–683why, one step back674 expect(data.ok).toBe(true)675 })676677 it('Should have correct types - basePath() then get()', async () => {678 const base = new Hono<Env>().basePath('/api')679 const app = base.get('/search', (c) => c.json({ ok: true }))680 type AppType = typeof app681 const client = hc<AppType>('http://localhost')682 const res = await client.api.search.$get()683 const data = await res.json()chore: update `typescript` to `5.9.2` (#4362)Yusuke Wadabefore adoption3e5a6e8
line 684why, one step back684 type verify = Expect<Equal<true, typeof data.ok>>chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 685–694why, one step back685 expect(data.ok).toBe(true)686 })687688 it('Should have correct types - basePath(), route(), get()', async () => {689 const book = new Hono().get('/', (c) => c.json({ ok: true }))690 const app = new Hono().basePath('/v1').route('/book', book)691 type AppType = typeof app692 const client = hc<AppType>('http://localhost')693 const res = await client.v1.book.$get()694 const data = await res.json()chore: update `typescript` to `5.9.2` (#4362)Yusuke Wadabefore adoption3e5a6e8
line 695why, one step back695 type verify = Expect<Equal<true, typeof data.ok>>chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 696–795why, one step back696 expect(data.ok).toBe(true)697 })698699 it('Should have correct types - with interface', async () => {700 interface Result {701 ok: boolean702 okUndefined?: boolean703 }704 const result: Result = { ok: true }705 const base = new Hono<Env>().basePath('/api')706 const app = base.get('/search', (c) => c.json(result))707 type AppType = typeof app708 const client = hc<AppType>('http://localhost')709 const res = await client.api.search.$get()710 const data = await res.json()711 type verify = Expect<Equal<Result, typeof data>>712 expect(data.ok).toBe(true)713714 // A few more types only tests715 interface DeepInterface {716 l2: {717 l3: Result718 }719 }720 interface ExtraDeepInterface {721 l4: DeepInterface722 }723 type verifyDeepInterface = Expect<724 Equal<SimplifyDeepArray<DeepInterface> extends JSONValue ? true : false, true>725 >726 type verifyExtraDeepInterface = Expect<727 Equal<SimplifyDeepArray<ExtraDeepInterface> extends JSONValue ? true : false, true>728 >729 })730731 it('Should have correct types - with array of interfaces', async () => {732 interface Result {733 ok: boolean734 okUndefined?: boolean735 }736 type Results = Result[]737738 const results: Results = [{ ok: true }]739 const base = new Hono<Env>().basePath('/api')740 const app = base.get('/searchArray', (c) => c.json(results))741 type AppType = typeof app742 const client = hc<AppType>('http://localhost')743 const res = await client.api.searchArray.$get()744 const data = await res.json()745 type verify = Expect<Equal<Results, typeof data>>746 expect(data[0].ok).toBe(true)747748 // A few more types only tests749 type verifyNestedArrayTyped = Expect<750 Equal<SimplifyDeepArray<[string, Results]> extends JSONValue ? true : false, true>751 >752 type verifyNestedArrayInterfaceArray = Expect<753 Equal<SimplifyDeepArray<[string, Result[]]> extends JSONValue ? true : false, true>754 >755 type verifyExtraNestedArrayTyped = Expect<756 Equal<SimplifyDeepArray<[string, Results[]]> extends JSONValue ? true : false, true>757 >758 type verifyExtraNestedArrayInterfaceArray = Expect<759 Equal<SimplifyDeepArray<[string, Result[][]]> extends JSONValue ? true : false, true>760 >761 })762763 it('Should allow a Date object and return it as a string', async () => {764 const app = new Hono()765 const route = app.get('/api/foo', (c) => c.json({ datetime: new Date() }))766 type AppType = typeof route767 const client = hc<AppType>('http://localhost')768 const res = await client.api.foo.$get()769 const { datetime } = await res.json()770 type verify = Expect<Equal<string, typeof datetime>>771 })772773 describe('Multiple endpoints', () => {774 const api = new Hono()775 .get('/foo', (c) => c.json({ foo: '' }))776 .post('/bar', (c) => c.json({ bar: 0 }))777 const app = new Hono().route('/api', api)778 type AppType = typeof app779 const client = hc<typeof app>('http://localhost')780781 it('Should return correct types - GET /api/foo', async () => {782 const res = await client.api.foo.$get()783 const data = await res.json()784 type verify = Expect<Equal<string, typeof data.foo>>785 })786787 it('Should return correct types - POST /api/bar', async () => {788 const res = await client.api.bar.$post()789 const data = await res.json()790 type verify = Expect<Equal<number, typeof data.bar>>791 })792 it('Should work with $url', async () => {793 const url = client.api.bar.$url()794 expect(url.href).toBe('http://localhost/api/bar')795 })Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
lines 796–799why, one step back796 it('Should work with $path', async () => {797 const path = client.api.bar.$path()798 expect(path).toBe('/api/bar')799 })chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 800–819why, one step back800 })801802 describe('With a blank path', () => {803 const app = new Hono().basePath('/api/v1')804 const routes = app.route(805 '/me',806 new Hono().route(807 '',808 new Hono().get('', async (c) => {809 return c.json({ name: 'hono' })810 })811 )812 )813 const client = hc<typeof routes>('http://localhost')814815 it('Should infer paths correctly', async () => {816 // Should not a throw type error817 const url = client.api.v1.me.$url()818 expectTypeOf<URL>(url)819 expect(url.href).toBe('http://localhost/api/v1/me')Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
lines 820–823why, one step back820821 const path = client.api.v1.me.$path()822 expectTypeOf<'/api/v1/me'>(path)823 expect(path).toBe('/api/v1/me')chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 824–825why, one step back824 })825 })Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
lines 826–850why, one step back826827 describe('With endpoint pathname', () => {828 const app = new Hono().basePath('/api/v1')829 const routes = app.route(830 '/me',831 new Hono().route(832 '',833 new Hono().get('', async (c) => {834 return c.json({ name: 'hono' })835 })836 )837 )838 const client = hc<typeof routes>('http://localhost/proxy')839840 it('Should infer paths correctly', async () => {841 // Should not a throw type error842 const url = client.api.v1.me.$url()843 expectTypeOf<URL>(url)844 expect(url.href).toBe('http://localhost/proxy/api/v1/me')845846 const path = client.api.v1.me.$path()847 expectTypeOf<'/api/v1/me'>(path)848 expect(path).toBe('/api/v1/me')849 })850 })chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 851–1017why, one step back851})852853describe('Use custom fetch method', () => {854 it('Should call the custom fetch method when provided', async () => {855 const fetchMock = vi.fn()856857 const api = new Hono().get('/search', (c) => c.json({ ok: true }))858 const app = new Hono().route('/api', api)859 type AppType = typeof app860 const client = hc<AppType>('http://localhost', { fetch: fetchMock })861 await client.api.search.$get()862 expect(fetchMock).toHaveBeenCalledTimes(1)863 })864865 it('Should return Response from custom fetch method', async () => {866 const fetchMock = vi.fn()867 const returnValue = new Response(null, { status: 200 })868 fetchMock.mockReturnValueOnce(returnValue)869870 const api = new Hono().get('/search', (c) => c.json({ ok: true }))871 const app = new Hono().route('/api', api)872 type AppType = typeof app873 const client = hc<AppType>('http://localhost', { fetch: fetchMock })874 const res = await client.api.search.$get()875 expect(res.ok).toBe(true)876 expect(res).toEqual(returnValue)877 })878})879880describe('Use custom fetch (app.request) method', () => {881 it('Should return Response from app request method', async () => {882 const app = new Hono().get('/search', (c) => c.json({ ok: true }))883 type AppType = typeof app884 const client = hc<AppType>('', { fetch: app.request })885 const res = await client.search.$get()886 expect(res.ok).toBe(true)887 })888})889890describe('Optional parameters in JSON response', () => {891 it('Should return the correct type', async () => {892 const app = new Hono().get('/', (c) => {893 return c.json({ message: 'foo' } as { message?: string })894 })895 type AppType = typeof app896 const client = hc<AppType>('', { fetch: app.request })897 const res = await client.index.$get()898 const data = await res.json()899 expectTypeOf(data).toEqualTypeOf<{900 message?: string901 }>()902 })903})904905describe('ClientResponse<T>.json() returns a Union type correctly', () => {906 const condition = () => true907 const app = new Hono().get('/', async (c) => {908 const ok = condition()909 if (ok) {910 return c.json({ data: 'foo' })911 }912 return c.json({ message: 'error' })913 })914915 const client = hc<typeof app>('', { fetch: app.request })916 it('Should be a Union type', async () => {917 const res = await client.index.$get()918 const json = await res.json()919 expectTypeOf(json).toEqualTypeOf<{ data: string } | { message: string }>()920 })921})922923describe('Response with different status codes', () => {924 const condition = () => true925 const app = new Hono().get('/', async (c) => {926 const ok = condition()927 if (ok) {928 return c.json({ data: 'foo' }, 200)929 }930 if (!ok) {931 return c.json({ message: 'error' }, 400)932 }933 return c.json(null)934 })935936 const client = hc<typeof app>('', { fetch: app.request })937938 it('all', async () => {939 const res = await client.index.$get()940 const json = await res.json()941 expectTypeOf(json).toEqualTypeOf<{ data: string } | { message: string } | null>()942 })943944 it('status 200', async () => {945 const res = await client.index.$get()946 if (res.status === 200) {947 const json = await res.json()948 expectTypeOf(json).toEqualTypeOf<{ data: string } | null>()949 }950 })951952 it('status 400', async () => {953 const res = await client.index.$get()954 if (res.status === 400) {955 const json = await res.json()956 expectTypeOf(json).toEqualTypeOf<{ message: string } | null>()957 }958 })959960 it('response is ok', async () => {961 const res = await client.index.$get()962 if (res.ok) {963 const json = await res.json()964 expectTypeOf(json).toEqualTypeOf<{ data: string } | null>()965 }966 })967968 it('response is not ok', async () => {969 const res = await client.index.$get()970 if (!res.ok) {971 const json = await res.json()972 expectTypeOf(json).toEqualTypeOf<{ message: string } | null>()973 }974 })975})976977describe('Infer the response type with different status codes', () => {978 const condition = () => true979 const app = new Hono().get('/', async (c) => {980 const ok = condition()981 if (ok) {982 return c.json({ data: 'foo' }, 200)983 }984 if (!ok) {985 return c.json({ message: 'error' }, 400)986 }987 return c.json(null)988 })989990 const client = hc<typeof app>('', { fetch: app.request })991992 it('Should infer response type correctly', () => {993 const req = client.index.$get994995 type Actual = InferResponseType<typeof req>996 type Expected =997 | {998 data: string999 }1000 | {1001 message: string1002 }1003 | null1004 type verify = Expect<Equal<Expected, Actual>>1005 })10061007 it('Should infer response type of status 200 correctly', () => {1008 const req = client.index.$get10091010 type Actual = InferResponseType<typeof req, 200>1011 type Expected = {1012 data: string1013 } | null1014 type verify = Expect<Equal<Expected, Actual>>1015 })1016})1017Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377
lines 1018–1123why, one step back1018describe('Infer the response types from middlewares', () => {1019 const app = new Hono()1020 .get(1021 '/',1022 validator('query', (input, c) => {1023 if (!input.page || typeof input.page !== 'string') {1024 return c.json({ error: 'Bad request' as const }, 400)1025 }10261027 return input as { page: string }1028 }),1029 async (c) => {1030 const query = c.req.valid('query')1031 return c.json({ data: 'foo', page: query.page }, 200)1032 }1033 )1034 .post(1035 '/posts',1036 async (c, next) => {1037 const auth = c.req.header('authorization')1038 if (!auth || !auth.startsWith('Bearer ')) {1039 return c.json({ error: 'Unauthorized' as const }, 401)1040 }1041 return next()1042 },1043 validator('json', (input, c) => {1044 if (!input.title) {1045 return c.json({ error: 'Bad request' as const }, 400)1046 }10471048 return input as { title: string }1049 }),1050 (c) => {1051 const data = c.req.valid('json')1052 return c.json(data, 200)1053 }1054 )10551056 type AppType = typeof app1057 const client = hc<AppType>('', { fetch: app.request })10581059 it('Should infer response type of status 200 correctly', () => {1060 const req = client.posts.$post10611062 type Actual = InferResponseType<typeof req, 200>1063 type Expected = {1064 title: string1065 }1066 type verify = Expect<Equal<Expected, Actual>>1067 })10681069 it('Should infer response type of status 400 correctly', () => {1070 const req = client.posts.$post10711072 type Actual = InferResponseType<typeof req, 400>1073 type Expected = {1074 error: 'Bad request'1075 }1076 type verify = Expect<Equal<Expected, Actual>>1077 })10781079 it('Should infer response type of status 401 correctly', () => {1080 const req = client.posts.$post10811082 type Actual = InferResponseType<typeof req, 401>1083 type Expected = {1084 error: 'Unauthorized'1085 }1086 type verify = Expect<Equal<Expected, Actual>>1087 })10881089 it('Should infer all possible response statuses', async () => {1090 const req = await client.posts.$post({1091 json: {1092 title: 'hello',1093 },1094 })10951096 type Actual = typeof req.status1097 type Expected = 200 | 400 | 4011098 type verify = Expect<Equal<Expected, Actual>>1099 })11001101 it('Should properly assign response to corresponding status', async () => {1102 const req = await client.posts.$post({1103 json: {1104 title: 'hello',1105 },1106 })11071108 if (req.status === 200) {1109 const data = await req.json()11101111 expectTypeOf(data).toEqualTypeOf<{ title: string }>()1112 } else if (req.status === 400) {1113 const data = await req.json()11141115 expectTypeOf(data).toEqualTypeOf<{ error: 'Bad request' }>()1116 } else if (req.status === 401) {1117 const data = await req.json()11181119 expectTypeOf(data).toEqualTypeOf<{ error: 'Unauthorized' }>()1120 }1121 })1122})1123Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
lines 1124–1127why, one step back1124const pathname = <T extends URL | string>(value: T): string =>1125 value instanceof URL ? value.pathname : value11261127describe.each(['$path', '$url'] as const)('%s() with a param option', (cmd) => {chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 1128–1133why, one step back1128 const app = new Hono()1129 .get('/posts/:id/comments', (c) => c.json({ ok: true }))1130 .get('/something/:firstId/:secondId/:version?', (c) => c.json({ ok: true }))1131 type AppType = typeof app1132 const client = hc<AppType>('http://localhost')1133Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
lines 1134–1135why, one step back1134 it('Should return the correct url path - /posts/123/comments', async () => {1135 const value = client.posts[':id'].comments[cmd]({chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 1136–1139why, one step back1136 param: {1137 id: '123',1138 },1139 })Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
line 1140why, one step back1140 expect(pathname(value)).toBe('/posts/123/comments')chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 1141–1143why, one step back1141 })11421143 it('Should return the correct path - /posts/:id/comments', async () => {Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
lines 1144–1145why, one step back1144 const value = client.posts[':id'].comments[cmd]()1145 expect(pathname(value)).toBe('/posts/:id/comments')chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 1146–1148why, one step back1146 })11471148 it('Should return the correct path - /something/123/456', async () => {Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
line 1149why, one step back1149 const value = client.something[':firstId'][':secondId'][':version?'][cmd]({chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 1150–1155why, one step back1150 param: {1151 firstId: '123',1152 secondId: '456',1153 version: undefined,1154 },1155 })Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
line 1156why, one step back1156 expect(pathname(value)).toBe('/something/123/456')chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 1157–1159why, one step back1157 })1158})1159Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
line 1160why, one step back1160describe('$url() / $path() with a query option', () => {chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 1161–1177why, one step back1161 const app = new Hono().get(1162 '/posts',1163 validator('query', () => {1164 return {} as { filter: 'test' }1165 }),1166 (c) => c.json({ ok: true })1167 )1168 type AppType = typeof app1169 const client = hc<AppType>('http://localhost')11701171 it('Should return the correct path - /posts?filter=test', async () => {1172 const url = client.posts.$url({1173 query: {1174 filter: 'test',1175 },1176 })1177 expect(url.search).toBe('?filter=test')Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
lines 1178–1184why, one step back11781179 const path = client.posts.$path({1180 query: {1181 filter: 'test',1182 },1183 })1184 expect(path).toBe('/posts?filter=test')chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 1185–1571why, one step back1185 })1186})11871188describe('Client can be awaited', () => {1189 it('Can be awaited without side effects', async () => {1190 const client = hc('http://localhost')11911192 const awaited = await client11931194 expect(awaited).toEqual(client)1195 })1196})11971198describe('Dynamic headers', () => {1199 const app = new Hono()12001201 const route = app.post('/posts', (c) => {1202 return c.json({1203 requestDynamic: 'dummy',1204 })1205 })12061207 type AppType = typeof route12081209 const server = setupServer(1210 http.post('http://localhost/posts', async ({ request }) => {1211 const requestDynamic = request.headers.get('x-dynamic')1212 const payload = {1213 requestDynamic,1214 }1215 return HttpResponse.json(payload)1216 })1217 )12181219 beforeAll(() => server.listen())1220 afterEach(() => server.resetHandlers())1221 afterAll(() => server.close())12221223 let dynamic = ''12241225 const client = hc<AppType>('http://localhost', {1226 headers: () => ({ 'x-hono': 'hono', 'x-dynamic': dynamic }),1227 })12281229 it('Should have "x-dynamic": "one"', async () => {1230 dynamic = 'one'12311232 const res = await client.posts.$post()12331234 expect(res.ok).toBe(true)1235 const data = await res.json()1236 expect(data.requestDynamic).toEqual('one')1237 })12381239 it('Should have "x-dynamic": "two"', async () => {1240 dynamic = 'two'12411242 const res = await client.posts.$post()12431244 expect(res.ok).toBe(true)1245 const data = await res.json()1246 expect(data.requestDynamic).toEqual('two')1247 })1248})12491250describe('RequestInit work as expected', () => {1251 const app = new Hono()12521253 const route = app1254 .get('/credentials', (c) => {1255 return c.text('' as RequestCredentials)1256 })1257 .get('/headers', (c) => {1258 return c.json({} as Record<string, string>)1259 })1260 .post('/headers', (c) => c.text('Not found', 404))12611262 type AppType = typeof route12631264 const server = setupServer(1265 http.get('http://localhost/credentials', ({ request }) => {1266 return HttpResponse.text(request.credentials)1267 }),1268 http.get('http://localhost/headers', ({ request }) => {1269 const allHeaders: Record<string, string> = {}1270 for (const [k, v] of request.headers.entries()) {1271 allHeaders[k] = v1272 }12731274 return HttpResponse.json(allHeaders)1275 }),1276 http.post('http://localhost/headers', () => {1277 return HttpResponse.text('Should not be here', {1278 status: 400,1279 })1280 })1281 )12821283 beforeAll(() => server.listen())1284 afterEach(() => server.resetHandlers())1285 afterAll(() => server.close())12861287 const client = hc<AppType>('http://localhost', {1288 headers: { 'x-hono': 'fire' },1289 init: {1290 credentials: 'include',1291 },1292 })12931294 it('Should overwrite method and fail', async () => {1295 const res = await client.headers.$get(undefined, { init: { method: 'POST' } })12961297 expect(res.ok).toBe(false)1298 })12991300 it('Should clear headers', async () => {1301 const res = await client.headers.$get(undefined, { init: { headers: undefined } })13021303 expect(res.ok).toBe(true)1304 const data = await res.json()1305 expect(data).toEqual({})1306 })13071308 it('Should overwrite headers', async () => {1309 const res = await client.headers.$get(undefined, {1310 init: { headers: new Headers({ 'x-hono': 'awesome' }) },1311 })13121313 expect(res.ok).toBe(true)1314 const data = await res.json()1315 expect(data).toEqual({ 'x-hono': 'awesome' })1316 })13171318 it('credentials is include', async () => {1319 const res = await client.credentials.$get()13201321 expect(res.ok).toBe(true)1322 const data = await res.text()1323 expect(data).toEqual('include')1324 })13251326 it('deepMerge should works and not unset credentials', async () => {1327 const res = await client.credentials.$get(undefined, { init: { headers: { hi: 'hello' } } })13281329 expect(res.ok).toBe(true)1330 const data = await res.text()1331 expect(data).toEqual('include')1332 })13331334 it('Should unset credentials', async () => {1335 const res = await client.credentials.$get(undefined, { init: { credentials: undefined } })13361337 expect(res.ok).toBe(true)1338 const data = await res.text()1339 expect(data).toEqual('same-origin')1340 })1341})13421343describe('WebSocket URL Protocol Translation', () => {1344 const app = new Hono()1345 const route = app.get(1346 '/',1347 upgradeWebSocket((c) => ({1348 onMessage(event, ws) {1349 console.log(`Message from client: ${event.data}`)1350 ws.send('Hello from server!')1351 },1352 onClose: () => {1353 console.log('Connection closed')1354 },1355 }))1356 )13571358 type AppType = typeof route13591360 const server = setupServer()1361 const webSocketMock = vi.fn()13621363 beforeAll(() => server.listen())1364 beforeEach(() => {1365 vi.stubGlobal('WebSocket', webSocketMock)1366 })1367 afterEach(() => {1368 vi.clearAllMocks()1369 server.resetHandlers()1370 })1371 afterAll(() => server.close())13721373 it('Translates HTTP to ws', async () => {1374 const client = hc<AppType>('http://localhost')1375 client.index.$ws()1376 expect(webSocketMock).toHaveBeenCalledWith('ws://localhost/index')1377 })13781379 it('Translates HTTPS to wss', async () => {1380 const client = hc<AppType>('https://localhost')1381 client.index.$ws()1382 expect(webSocketMock).toHaveBeenCalledWith('wss://localhost/index')1383 })13841385 it('Keeps ws unchanged', async () => {1386 const client = hc<AppType>('ws://localhost')1387 client.index.$ws()1388 expect(webSocketMock).toHaveBeenCalledWith('ws://localhost/index')1389 })13901391 it('Keeps wss unchanged', async () => {1392 const client = hc<AppType>('wss://localhost')1393 client.index.$ws()1394 expect(webSocketMock).toHaveBeenCalledWith('wss://localhost/index')1395 })1396})13971398describe('WebSocket URL Protocol Translation with Query Parameters', () => {1399 const app = new Hono()1400 const route = app.get(1401 '/',1402 upgradeWebSocket((c) => ({1403 onMessage(event, ws) {1404 ws.send('Hello from server!')1405 },1406 onClose: () => {1407 console.log('Connection closed')1408 },1409 }))1410 )14111412 type AppType = typeof route14131414 const server = setupServer()1415 const webSocketMock = vi.fn()14161417 beforeAll(() => server.listen())1418 beforeEach(() => {1419 vi.stubGlobal('WebSocket', webSocketMock)1420 })1421 afterEach(() => {1422 vi.clearAllMocks()1423 server.resetHandlers()1424 })1425 afterAll(() => server.close())14261427 it('Translates HTTP to ws and includes query parameters', async () => {1428 const client = hc<AppType>('http://localhost')1429 client.index.$ws({1430 query: {1431 id: '123',1432 type: 'test',1433 tag: ['a', 'b'],1434 },1435 })1436 expect(webSocketMock).toHaveBeenCalledWith('ws://localhost/index?id=123&type=test&tag=a&tag=b')1437 })14381439 it('Translates HTTPS to wss and includes query parameters', async () => {1440 const client = hc<AppType>('https://localhost')1441 client.index.$ws({1442 query: {1443 id: '456',1444 type: 'secure',1445 },1446 })1447 expect(webSocketMock).toHaveBeenCalledWith('wss://localhost/index?id=456&type=secure')1448 })14491450 it('Keeps ws unchanged and includes query parameters', async () => {1451 const client = hc<AppType>('ws://localhost')1452 client.index.$ws({1453 query: {1454 id: '789',1455 type: 'plain',1456 },1457 })1458 expect(webSocketMock).toHaveBeenCalledWith('ws://localhost/index?id=789&type=plain')1459 })14601461 it('Keeps wss unchanged and includes query parameters', async () => {1462 const client = hc<AppType>('wss://localhost')1463 client.index.$ws({1464 query: {1465 id: '1011',1466 type: 'secure',1467 },1468 })1469 expect(webSocketMock).toHaveBeenCalledWith('wss://localhost/index?id=1011&type=secure')1470 })1471})14721473describe('Client can be console.log in react native', () => {1474 it('Returns a function name with function.name.toString', async () => {1475 const client = hc('http://localhost')1476 // @ts-ignore1477 expect(client.posts.name.toString()).toEqual('posts')1478 })14791480 it('Returns a function name with function.name.valueOf', async () => {1481 const client = hc('http://localhost')1482 // @ts-ignore1483 expect(client.posts.name.valueOf()).toEqual('posts')1484 })14851486 it('Returns a function with function.valueOf', async () => {1487 const client = hc('http://localhost')1488 expect(typeof client.posts.valueOf()).toEqual('function')1489 })14901491 it('Returns a function source with function.toString', async () => {1492 const client = hc('http://localhost')1493 expect(client.posts.toString()).toMatch('function proxyCallback')1494 })1495})14961497describe('Text response', () => {1498 const text = 'My name is Hono'1499 const obj = { ok: true }1500 const server = setupServer(1501 http.get('http://localhost/about/me', async () => {1502 return HttpResponse.text(text)1503 }),1504 http.get('http://localhost/api', async ({ request }) => {1505 return HttpResponse.json(obj)1506 })1507 )15081509 beforeAll(() => server.listen())1510 afterEach(() => server.resetHandlers())1511 afterAll(() => server.close())15121513 const app = new Hono().get('/about/me', (c) => c.text(text)).get('/api', (c) => c.json(obj))1514 const client = hc<typeof app>('http://localhost/')15151516 it('Should be never with res.json() - /about/me', async () => {1517 const res = await client.about.me.$get()1518 type Actual = ReturnType<typeof res.json>1519 type Expected = Promise<never>1520 type verify = Expect<Equal<Expected, Actual>>1521 })15221523 it('Should be "Hello, World!" with res.text() - /about/me', async () => {1524 const res = await client.about.me.$get()1525 const data = await res.text()1526 expectTypeOf(data).toEqualTypeOf<'My name is Hono'>()1527 expect(data).toBe(text)1528 })15291530 /**1531 * Also check the type of JSON response with res.text().1532 */1533 it('Should be string with res.text() - /api', async () => {1534 const res = await client.api.$get()1535 type Actual = ReturnType<typeof res.text>1536 type Expected = Promise<string>1537 type verify = Expect<Equal<Expected, Actual>>1538 })1539})15401541describe('Redirect response - only types', () => {1542 const server = setupServer(1543 http.get('http://localhost/', async () => {1544 return HttpResponse.redirect('/')1545 })1546 )15471548 beforeAll(() => server.listen())1549 afterEach(() => server.resetHandlers())1550 afterAll(() => server.close())15511552 const condition = () => true1553 const app = new Hono().get('/', async (c) => {1554 const ok = condition()1555 const temporary = condition()1556 if (ok) {1557 return c.json({ ok: true }, 200)1558 }1559 if (temporary) {1560 return c.redirect('/302')1561 }1562 return c.redirect('/301', 301)1563 })15641565 const client = hc<typeof app>('http://localhost/')1566 const req = client.index.$get15671568 it('Should infer request type the type correctly', () => {1569 type Actual = InferResponseType<typeof req>1570 type Expected =1571 | {chore: update `typescript` to `5.9.2` (#4362)Yusuke Wadabefore adoption3e5a6e8
line 1572why, one step back1572 ok: truechore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626
lines 1573–1642why, one step back1573 }1574 | undefined1575 type verify = Expect<Equal<Expected, Actual>>1576 })15771578 it('Should infer response type correctly', async () => {1579 const res = await req()1580 if (res.ok) {1581 const data = await res.json()1582 expectTypeOf(data).toMatchTypeOf({ ok: true })1583 }1584 if (res.status === 301) {1585 type Expected = ClientResponse<undefined, 301, 'redirect'>1586 type verify = Expect<Equal<Expected, typeof res>>1587 }1588 if (res.status === 302) {1589 type Expected = ClientResponse<undefined, 302, 'redirect'>1590 type verify = Expect<Equal<Expected, typeof res>>1591 }1592 })1593})15941595describe('WebSocket Provider Integration', () => {1596 const app = new Hono()1597 const route = app.get(1598 '/',1599 upgradeWebSocket((c) => ({1600 onMessage(event, ws) {1601 ws.send('Hello from server!')1602 },1603 onClose() {1604 console.log('Connection closed')1605 },1606 }))1607 )16081609 type AppType = typeof route16101611 const server = setupServer()1612 beforeAll(() => server.listen())1613 afterEach(() => {1614 vi.clearAllMocks()1615 server.resetHandlers()1616 })1617 afterAll(() => server.close())16181619 it.each([1620 {1621 description: 'should initialize the WebSocket provider correctly',1622 url: 'http://localhost',1623 query: undefined,1624 expectedUrl: 'ws://localhost/index',1625 },1626 {1627 description: 'should correctly add query parameters to the WebSocket URL',1628 url: 'http://localhost',1629 query: { id: '123', type: 'test', tag: ['a', 'b'] },1630 expectedUrl: 'ws://localhost/index?id=123&type=test&tag=a&tag=b',1631 },1632 ])('$description', ({ url, expectedUrl, query }) => {1633 const webSocketMock = vi.fn()1634 const client = hc<AppType>(url, {1635 webSocket(url, options) {1636 return webSocketMock(url, options)1637 },1638 })1639 client.index.$ws({ query })1640 expect(webSocketMock).toHaveBeenCalledWith(expectedUrl, undefined)1641 })1642})Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
lines 1643–1678why, one step back16431644describe('Custom buildSearchParams', () => {1645 const app = new Hono()1646 const route = app.get(1647 '/search',1648 validator('query', () => {1649 return {} as { q: string; tags: string[] }1650 }),1651 (c) => {1652 return c.json({1653 message: 'success',1654 queryString: '',1655 })1656 }1657 )16581659 type AppType = typeof route16601661 const server = setupServer(1662 http.get('http://localhost/search', ({ request }) => {1663 const url = new URL(request.url)1664 return HttpResponse.json({1665 message: 'success',1666 queryString: url.search,1667 })1668 })1669 )16701671 beforeAll(() => server.listen())1672 afterEach(() => server.resetHandlers())1673 afterAll(() => server.close())16741675 // Custom buildSearchParams that uses bracket notation for arrays (key[]=value)1676 const customBuildSearchParams = (query: Record<string, string | string[]>) => {1677 const searchParams = new URLSearchParams()1678 for (const [k, v] of Object.entries(query)) {chore: bump `@hono/eslint-config` and enable curly rule (#4620)Yusuke Wadabefore adoption8139399
lines 1679–1681why, one step back1679 if (v === undefined) {1680 continue1681 }Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
lines 1682–1720why, one step back1682 if (Array.isArray(v)) {1683 v.forEach((item) => searchParams.append(`${k}[]`, item))1684 } else {1685 searchParams.set(k, v)1686 }1687 }1688 return searchParams1689 }16901691 it('Should use custom buildSearchParams for query serialization', async () => {1692 const client = hc<AppType>('http://localhost', { buildSearchParams: customBuildSearchParams })1693 const res = await client.search.$get({ query: { q: 'test', tags: ['tag1', 'tag2', 'tag3'] } })1694 const data = await res.json()16951696 expect(res.status).toBe(200)1697 expect(data.queryString).toBe('?q=test&tags%5B%5D=tag1&tags%5B%5D=tag2&tags%5B%5D=tag3')1698 })16991700 it('Should use default buildSearchParams when custom one is not provided', async () => {1701 const client = hc<AppType>('http://localhost')1702 const res = await client.search.$get({ query: { q: 'test', tags: ['tag1', 'tag2'] } })1703 const data = await res.json()17041705 expect(res.status).toBe(200)1706 expect(data.queryString).toBe('?q=test&tags=tag1&tags=tag2')1707 })17081709 it('Should use custom buildSearchParams in $url() method', () => {1710 const client = hc<AppType>('http://localhost', { buildSearchParams: customBuildSearchParams })1711 const url = client.search.$url({ query: { q: 'test', tags: ['tag1', 'tag2'] } })17121713 expect(url.href).toBe('http://localhost/search?q=test&tags%5B%5D=tag1&tags%5B%5D=tag2')1714 })17151716 it('Should use default buildSearchParams in $url() when custom one is not provided', () => {1717 const client = hc<AppType>('http://localhost')1718 const url = client.search.$url({ query: { q: 'test', tags: ['tag1', 'tag2'] } })17191720 expect(url.href).toBe('http://localhost/search?q=test&tags=tag1&tags=tag2')Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
lines 1721–1824why, one step back1721 })1722})17231724describe('ApplyGlobalResponse Type Helper', () => {1725 const server = setupServer(1726 http.get('http://localhost/api/users', () => {1727 return HttpResponse.json({ users: ['alice', 'bob'] })1728 }),1729 http.get('http://localhost/api/error', () => {1730 return HttpResponse.json(1731 { error: 'Internal Server Error', message: 'Something went wrong' },1732 { status: 500 }1733 )1734 }),1735 http.get('http://localhost/api/unauthorized', () => {1736 return HttpResponse.json({ error: 'Unauthorized', message: 'Please login' }, { status: 401 })1737 })1738 )17391740 beforeAll(() => server.listen())1741 afterEach(() => server.resetHandlers())1742 afterAll(() => server.close())17431744 it('Should add global error response types to all routes', () => {1745 // Use explicit status codes for proper type narrowing1746 const app = new Hono().get('/api/users', (c) => c.json({ users: ['alice', 'bob'] }, 200))17471748 // Apply global error responses with new object syntax1749 type AppWithGlobalErrors = ApplyGlobalResponse<1750 typeof app,1751 {1752 401: { json: { error: string; message: string } }1753 500: { json: { error: string; message: string } }1754 }1755 >17561757 const client = hc<AppWithGlobalErrors>('http://localhost')1758 const req = client.api.users.$get17591760 // Type should be a union of normal response and global errors1761 type ResponseType = InferResponseType<typeof req>1762 type Expected = { users: string[] } | { error: string; message: string }17631764 type verify = Expect<Equal<ResponseType, Expected>>1765 })17661767 it('Should support multiple global error status codes', async () => {1768 const app = new Hono()1769 .get('/api/users', (c) => c.json({ users: ['alice', 'bob'] }, 200))1770 .get('/api/unauthorized', (c) =>1771 c.json({ error: 'Unauthorized', message: 'Please login' }, 401)1772 )1773 .get('/api/error', (c) =>1774 c.json({ error: 'Internal Server Error', message: 'Something went wrong' }, 500)1775 )17761777 // Apply multiple global error types in one definition1778 type AppWithGlobalErrors = ApplyGlobalResponse<1779 typeof app,1780 {1781 401: { json: { error: string; message: string } }1782 500: { json: { error: string; message: string } }1783 }1784 >17851786 const client = hc<AppWithGlobalErrors>('http://localhost')17871788 // Verify runtime behavior for different status codes1789 const usersRes = await client.api.users.$get()1790 expect(usersRes.status).toBe(200)17911792 const unauthorizedRes = await client.api.unauthorized.$get()1793 expect(unauthorizedRes.status).toBe(401)1794 expect(await unauthorizedRes.json()).toEqual({ error: 'Unauthorized', message: 'Please login' })17951796 const errorRes = await client.api.error.$get()1797 expect(errorRes.status).toBe(500)1798 expect(await errorRes.json()).toEqual({1799 error: 'Internal Server Error',1800 message: 'Something went wrong',1801 })1802 })18031804 it('Should work with onError handler pattern', () => {1805 // Simulating typical Hono app with onError handler1806 // Use explicit status code for proper type narrowing1807 const app = new Hono().get('/api/users', (c) => c.json({ users: ['alice', 'bob'] }, 200))18081809 // In real app: app.onError((err, c) => c.json({ error: err.message }, 500))1810 type AppWithOnError = ApplyGlobalResponse<1811 typeof app,1812 {1813 500: { json: { error: string } }1814 }1815 >18161817 const client = hc<AppWithOnError>('http://localhost')1818 const req = client.api.users.$get18191820 // RPC client should know about the error format1821 type ResponseType = InferResponseType<typeof req>1822 type Expected = { users: string[] } | { error: string }18231824 type verify = Expect<Equal<ResponseType, Expected>>Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
line 1825why, one step back1825 })fix(client): preserve route schema in ApplyGlobalResponse (#4777)Oguma Shunyabefore adoption0768232
lines 1826–1843why, one step back18261827 it('Should keep route() paths when global responses are applied', () => {1828 const users = new Hono().get('/users', (c) => c.json({ users: ['alice', 'bob'] }, 200))1829 const app = new Hono().route('/api', users)18301831 type AppWithGlobalErrors = ApplyGlobalResponse<1832 typeof app,1833 {1834 500: { json: { error: string } }1835 }1836 >18371838 const client = hc<AppWithGlobalErrors>('http://localhost')1839 const req = client.api.users.$get18401841 type ResponseType = InferResponseType<typeof req>1842 type Expected = { users: string[] } | { error: string }1843feat(client): add `PickResponseByStatusCode` type (#4791)Yusuke Wadabefore adoptiond1722e3
lines 1844–1941why, one step back1844 type verify = Expect<Equal<ResponseType, Expected>>1845 })1846})18471848describe('PickResponseByStatusCode Type Helper', () => {1849 it('Should keep only specified status code responses', () => {1850 const app = new Hono().get('/api/users', (c) => {1851 try {1852 return c.json({ users: ['alice', 'bob'] }, 200)1853 } catch {1854 return c.json({ error: 'Internal Server Error' }, 500)1855 }1856 })18571858 type AppSuccessOnly = PickResponseByStatusCode<typeof app, 200>18591860 const client = hc<AppSuccessOnly>('http://localhost')1861 const req = client.api.users.$get18621863 type ResponseType = InferResponseType<typeof req>1864 type Expected = { users: string[] }1865 type verify = Expect<Equal<ResponseType, Expected>>18661867 type Res = Awaited<ReturnType<typeof req>>1868 type verifyOk = Expect<Equal<Res['ok'], true>>1869 type verifyStatus = Expect<Equal<Res['status'], 200>>1870 })18711872 it('Should work with ApplyGlobalResponse', () => {1873 const app = new Hono().get('/api/users', (c) => {1874 try {1875 return c.json({ users: ['alice', 'bob'] }, 200)1876 } catch {1877 return c.json({ error: 'Not Found' }, 404)1878 }1879 })18801881 type AppWithGlobalErrors = ApplyGlobalResponse<1882 typeof app,1883 {1884 401: { json: { error: string; message: string } }1885 500: { json: { error: string; message: string } }1886 }1887 >18881889 type AppSuccessOnly = PickResponseByStatusCode<AppWithGlobalErrors, 200>18901891 const client = hc<AppSuccessOnly>('http://localhost')1892 const req = client.api.users.$get18931894 type ResponseType = InferResponseType<typeof req>1895 type Expected = { users: string[] }1896 type verify = Expect<Equal<ResponseType, Expected>>1897 })18981899 it('Should work with route() paths', () => {1900 const users = new Hono().get('/users', (c) => {1901 try {1902 return c.json({ users: ['alice', 'bob'] }, 200)1903 } catch {1904 return c.json({ error: 'error' }, 500)1905 }1906 })1907 const app = new Hono().route('/api', users)19081909 type AppSuccessOnly = PickResponseByStatusCode<typeof app, 200>19101911 const client = hc<AppSuccessOnly>('http://localhost')1912 const req = client.api.users.$get19131914 type ResponseType = InferResponseType<typeof req>1915 type Expected = { users: string[] }1916 type verify = Expect<Equal<ResponseType, Expected>>1917 })19181919 it('Should pick multiple status codes', () => {1920 const app = new Hono().get('/api/users', (c) => {1921 try {1922 return c.json({ users: ['alice', 'bob'] }, 200)1923 } catch {1924 return c.json({ error: 'Bad Request' }, 400)1925 }1926 })19271928 type AppWithGlobalErrors = ApplyGlobalResponse<1929 typeof app,1930 {1931 500: { json: { error: string } }1932 }1933 >19341935 type AppFiltered = PickResponseByStatusCode<AppWithGlobalErrors, 200 | 400>19361937 const client = hc<AppFiltered>('http://localhost')1938 const req = client.api.users.$get19391940 type ResponseType = InferResponseType<typeof req>1941 type Expected = { users: string[] } | { error: string }fix(client): preserve route schema in ApplyGlobalResponse (#4777)Oguma Shunyabefore adoption0768232
lines 1942–1943why, one step back1942 type verify = Expect<Equal<ResponseType, Expected>>1943 })Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
line 1944why, one step back1944})