Skip to content
Myr

fix(parseResponse): should not include error responses in result (#4348)

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

* fix(client): improve parseResponse type inference for conditional responses Previously, parseResponse would infer union types for routes that return different response types based on conditions (e.g., success vs error responses). This was incorrect because parseResponse throws errors for non-OK responses and should only return the success response type. Changes: - Use Extract<> utility type to filter success status code responses from union types - Add fallback logic for responses without explicit success status codes - Update test cases to match the corrected behavior - Add comprehensive test case for conditional response type inference The fix ensures that parseResponse(client['conditional-route'].$get()) correctly infers only the success response type instead of a union of all possible response types. * ci: apply automated fixes * test(client): fix parsedResponse test issue and remove unused test case * fix: minor type error in current runtime version * chore: add more test cases * feat: add `FilterClientResponses` util * fix(parseResponse): should not include error responses in result * chore: refactor to type-only tests and ordering * chore: rename type util and add JSDOC describe ---------

authored by Trung Dang · committed by GitHub · parent 855e5b1 · Browse files · 3 files+89 added−5 removed
This commit

State

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

Trailers

  • Co-authored-by: Zed tse <joexie@live.cn>
  • Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>

Diff stats

3 files+89 added−5 removed

  • tests:+59 added−2 removed
  • other:+30 added−3 removed

3 files+89 added−5 removed

modified:src/client/types.ts+12 added
modified:src/client/utils.test.ts+59 added-2 removed
148 unmodified lines
149describe('parseResponse', async () => {150 const app = new Hono()151 .get('/text', (c) => c.text('hi'))152 .get('/json', (c) => c.json({ message: 'hi' }))153 .get('/404', (c) => c.notFound())153 .get('/might-error-json', (c) => {154 if (Math.random() > 0.5) {155 return c.json({ error: 'error' }, 500)156 }157 return c.json({ data: [{ id: 1 }, { id: 2 }] })158 })159 .get('/might-error-mixed-json-text', (c) => {160 if (Math.random() > 0.5) {161 return c.text('500 Internal Server Error', 500)162 }163 return c.json({ message: 'Success' })164 })165 .get('/200-explicit', (c) => c.text('OK', 200))166 .get('/404', (c) => c.text('404 Not Found', 404))167 .get('/500', (c) => c.text('500 Internal Server Error', 500))168 .get('/raw', (c) => {169 c.header('content-type', '')170 return c.body('hello')
15 unmodified lines
186 }),187 http.get('http://localhost/json', () => {188 return HttpResponse.json({ message: 'hi' })189 }),190 http.get('http://localhost/might-error-json', () => {191 if (Math.random() > 0.5) {192 return HttpResponse.json({ error: 'error' }, { status: 500 })193 }194 return HttpResponse.json({ data: [{ id: 1 }, { id: 2 }] })195 }),196 http.get('http://localhost/might-error-mixed-json-text', () => {197 if (Math.random() > 0.5) {198 return HttpResponse.text('500 Internal Server Error', { status: 500 })199 }200 return HttpResponse.json({ message: 'Success' })201 }),202 http.get('http://localhost/200-explicit', () => {203 return HttpResponse.text('OK', { status: 200 })204 }),205 http.get('http://localhost/404', () => {206 return HttpResponse.text('404 Not Found', { status: 404 })207 }),208 http.get('http://localhost/500', () => {
13 unmodified lines
222 },223 })224 }),225 http.get('http://localhost/rawBuffer', () => {198 return HttpResponse.arrayBuffer(new TextEncoder().encode('hono'), {226 return HttpResponse.arrayBuffer(new TextEncoder().encode('hono').buffer, {227 headers: {228 'content-type': 'x/custom-type',229 },230 })
14 unmodified lines
245 const result = await parseResponse(await client.text.$get())246 expect(result).toBe('hi')247 type _verify = Expect<Equal<typeof result, 'hi'>>248 }),249 it('should auto parse text response - explicit 200', async () => {250 const result = await parseResponse(client['200-explicit'].$get())251 expect(result).toBe('OK')252 type _verify = Expect<Equal<typeof result, 'OK'>>253 }),254 it('should auto parse the json response - async fetch', async () => {255 const result = await parseResponse(client.json.$get())256 expect(result).toEqual({ message: 'hi' })257 type _verify = Expect<Equal<typeof result, { message: string }>>
33 unmodified lines
291 // @ts-expect-error noRoute is not defined292 parseResponse(client['noRoute'].$get())293 ).rejects.toThrowErrorMatchingInlineSnapshot('[TypeError: fetch failed]')294 }),295 it('(type-only) should bypass error responses in the result type inference - simple 404', async () => {296 type ResultType = Awaited<297 ReturnType<typeof parseResponse<Awaited<ReturnType<(typeof client)['404']['$get']>>>>298 >299 type _verify = Expect<Equal<Awaited<ResultType>, undefined>>300 }),301 it('(type-only) should bypass error responses in the result type inference - conditional - json', async () => {302 type ResultType = Awaited<303 ReturnType<304 typeof parseResponse<Awaited<ReturnType<(typeof client)['might-error-json']['$get']>>>305 >306 >307 type _verify = Expect<Equal<ResultType, { data: { id: number }[] }>>308 }),309 it('(type-only) should bypass error responses in the result type inference - conditional - mixed json/text', async () => {310 type ResultType = Awaited<311 ReturnType<312 typeof parseResponse<313 Awaited<ReturnType<(typeof client)['might-error-mixed-json-text']['$get']>>314 >315 >316 >317 type _verify = Expect<Equal<ResultType, { message: string }>>318 }),319 ])320})
modified:src/client/utils.ts+18 added-3 removed
1import type {2 ClientErrorStatusCode,3 ContentfulStatusCode,4 ServerErrorStatusCode,5} from '../utils/http-status'6import { fetchRP, DetailedError } from './fetch-result-please'2import type { ClientResponse, ObjectType } from './types'7import type { ClientResponse, FilterClientResponseByStatusCode, ObjectType } from './types'89export { DetailedError }1011export const mergePath = (base: string, path: string) => {
79 unmodified lines
91// eslint-disable-next-line @typescript-eslint/no-explicit-any92export async function parseResponse<T extends ClientResponse<any>>(93 fetchRes: T | Promise<T>94): Promise<95 FilterClientResponseByStatusCode<96 T,97 Exclude<ContentfulStatusCode, ClientErrorStatusCode | ServerErrorStatusCode> // Filter out the error responses98 > extends never99 ? // Filtered responses does not include any contentful responses, exit with undefined100 undefined101 : // Filtered responses includes contentful responses, proceed to infer the type102 FilterClientResponseByStatusCode<103 T,104 Exclude<ContentfulStatusCode, ClientErrorStatusCode | ServerErrorStatusCode>90 T extends ClientResponse<infer RT, infer _, infer RF>105 > extends ClientResponse<infer RT, infer _, infer RF>106 ? RF extends 'json'107 ? RT108 : RT extends string109 ? RT110 : string96 : never111 : undefined112> {113 return fetchRP(fetchRes)114}