feat: add `parseResponse` util to smartly parse `hc`'s Response (#4314)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat: add `hcParse` util to smartly parse response from a `hc` fetch * chore: alternative version with 0 deps * chore: simplify the inlined `fetchRP`, more tests * chore: remove `switch` wrap * types: correct infer when format is not `'json' | 'text'` * chore: tests for `c.body` with type inference * test: use `msw` instead of running an actual server * test: fix the test * chore: some rewording * test: `rawBuffer` should return buffer response * chore: rename and add file description + ref link * chore: rename `hcParse` => `parseResponse` ---------
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Yusuke Wada <yusuke@kamawada.com>
Diff stats
4 files+212 added−1 removed
- tests:+100 added−0 removed
- other:+112 added−1 removed
Provenance
- Commit
cd9629d- Tree
856471e- Author
Trung Dang <dangquoctrung123@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
0839066
4 files changed+212 added−1 removed
added:src/client/fetch-result-please.ts+85 added
1+/**2+ * @description This file is a modified version of `fetch-result-please` (`ofetch`), minimalized and adapted to Hono's custom needs.3+ *4+ * @link https://www.npmjs.com/package/fetch-result-please5+ */6+7+const nullBodyResponses = new Set([101, 204, 205, 304])8+9+/**10+ * Smartly parses and return the consumable result from a fetch `Response`.11+ *12+ * Throwing a structured error if the response is not `ok`. ({@link DetailedError})13+ */14+export async function fetchRP(fetchRes: Response | Promise<Response>): Promise<any> {15+ const _fetchRes = (await fetchRes) as unknown as Response & { _data: any }16+17+ const hasBody = _fetchRes.body && !nullBodyResponses.has(_fetchRes.status)18+19+ if (hasBody) {20+ const responseType = detectResponseType(_fetchRes)21+ _fetchRes._data = await _fetchRes[responseType]()22+ }23+24+ if (!_fetchRes.ok) {25+ throw new DetailedError(`${_fetchRes.status} ${_fetchRes.statusText}`, {26+ statusCode: _fetchRes?.status,27+ detail: {28+ data: _fetchRes?._data,29+ statusText: _fetchRes?.statusText,30+ },31+ })32+ }33+34+ return _fetchRes._data35+}36+37+export class DetailedError extends Error {38+ /**39+ * Additional `message` that will be logged AND returned to client40+ */41+ public detail?: any42+ /**43+ * Additional `code` that will be logged AND returned to client44+ */45+ public code?: any46+ /**47+ * Additional value that will be logged AND NOT returned to client48+ */49+ public log?: any50+ /**51+ * Optionally set the status code to return, in a web server context52+ */53+ public statusCode?: any54+55+ constructor(56+ message: string,57+ options: { detail?: any; code?: any; statusCode?: number; log?: any } = {}58+ ) {59+ super(message)60+ this.log = options.log61+ this.detail = options.detail62+ this.code = options.code63+ this.statusCode = options.statusCode64+ }65+}66+67+// This is used to match the content-type header for 'json'68+const jsonRegex = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(?:;.+)?$/i69+70+function detectResponseType(response: Response): 'json' | 'text' {71+ const _contentType = response.headers.get('content-type')72+73+ if (!_contentType) {74+ return 'text'75+ }76+77+ // `_contentType` might look like: `application/json; charset=utf-8`, `text/plain`, so we get the first part before `;`78+ const contentType = _contentType.split(';').shift()!79+80+ if (jsonRegex.test(contentType)) {81+ return 'json'82+ }83+84+ return 'text'85+}modified:src/client/index.ts+1 added
2 unmodified lines345678910114 unmodified lines2 unmodified lines * The HTTP Client for Hono. */
export { hc } from './client'export { parseResponse, DetailedError } from './utils'export type { InferResponseType, InferRequestType, Fetch,4 unmodified linesmodified:src/client/utils.test.ts+100 added
1+import { HttpResponse, http } from 'msw'2+import { setupServer } from 'msw/node'3+import { Hono } from '../hono'4+import type { Expect, Equal } from '../utils/types'5+import { hc } from './client'6 import {7 buildSearchParams,8 deepMerge,9+ parseResponse,10 mergePath,11 removeIndexString,12 replaceUrlParam,13 replaceUrlProtocol,130 unmodified lines144 timeout: 2,145 })146 })147 })148+149+describe('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())154+ .get('/raw', (c) => {155+ c.header('content-type', '')156+ return c.body('hello')157+ })158+ .get('/rawUnknown', (c) => {159+ c.header('content-type', 'x/custom-type')160+ return c.body('hello')161+ })162+ .get('/rawBuffer', (c) => {163+ c.header('content-type', 'x/custom-type')164+ return c.body(new TextEncoder().encode('hono'))165+ })166+167+ const client = hc<typeof app>('http://localhost')168+169+ const server = setupServer(170+ http.get('http://localhost/text', () => {171+ return HttpResponse.text('hi')172+ }),173+ http.get('http://localhost/json', () => {174+ return HttpResponse.json({ message: 'hi' })175+ }),176+ http.get('http://localhost/404', () => {177+ return HttpResponse.text('404 Not Found', { status: 404 })178+ }),179+ http.get('http://localhost/raw', () => {180+ return HttpResponse.text('hello', {181+ headers: {182+ 'content-type': '',183+ },184+ })185+ }),186+ http.get('http://localhost/rawUnknown', () => {187+ return HttpResponse.text('hello', {188+ headers: {189+ 'content-type': 'x/custom-type',190+ },191+ })192+ }),193+ http.get('http://localhost/rawBuffer', () => {194+ return HttpResponse.arrayBuffer(new TextEncoder().encode('hono'), {195+ headers: {196+ 'content-type': 'x/custom-type',197+ },198+ })199+ })200+ )201+202+ beforeAll(() => server.listen())203+ afterEach(() => server.resetHandlers())204+ afterAll(() => server.close())205+206+ await Promise.all([207+ it('should auto parse the text response - async fetch', async () => {208+ const result = await parseResponse(client.text.$get())209+ expect(result).toBe('hi')210+ type _verify = Expect<Equal<typeof result, 'hi'>>211+ }),212+ it('should auto parse the text response - sync fetch', async () => {213+ const result = await parseResponse(await client.text.$get())214+ expect(result).toBe('hi')215+ type _verify = Expect<Equal<typeof result, 'hi'>>216+ }),217+ it('should auto parse the json response - async fetch', async () => {218+ const result = await parseResponse(client.json.$get())219+ expect(result).toEqual({ message: 'hi' })220+ type _verify = Expect<Equal<typeof result, { message: string }>>221+ }),222+ it('should auto parse the json response - sync fetch', async () => {223+ const result = await parseResponse(await client.json.$get())224+ expect(result).toEqual({ message: 'hi' })225+ type _verify = Expect<Equal<typeof result, { message: string }>>226+ }),227+ it('should throw error when the response is not ok', async () => {228+ await expect(parseResponse(client['404'].$get())).rejects.toThrowError('404 Not Found')229+ }),230+ it('should parse as text for raw responses without content-type header', async () => {231+ const result = await parseResponse(client.raw.$get())232+ expect(result).toBe('hello')233+ type _verify = Expect<Equal<typeof result, 'hello'>>234+ }),235+ it('should parse as unknown string for raw buffer responses with unknown content-type header', async () => {236+ const result = await parseResponse(client.rawBuffer.$get())237+ expect(result).toMatchInlineSnapshot('"hono"')238+ type _verify = Expect<Equal<typeof result, string>>239+ }),240+ ])241+})modified:src/client/utils.ts+26 added-1 removed
112345678964 unmodified lines7475767778798081828384858687888990919293949596979899import { fetchRP, DetailedError } from './fetch-result-please'import type { ObjectType } from './types'import type { ClientResponse, ObjectType } from './types'
export { DetailedError }
export const mergePath = (base: string, path: string) => { base = base.replace(/\/+$/, '') base = base + '/' path = path.replace(/^\/+/, '')64 unmodified lines }
return merged as T}
/** * Shortcut to get a consumable response from `hc`'s fetch calls (Response), with types inference. * * Smartly parse the response data, throwing a structured error if the response is not `ok`. ({@link DetailedError}) * * @example const result = await parseResponse(client.posts.$get()) */// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport async function parseResponse<T extends ClientResponse<any>>( fetchRes: T | Promise<T>): Promise< T extends ClientResponse<infer RT, infer _, infer RF> ? RF extends 'json' ? RT : RT extends string ? RT : string : never> { return fetchRP(fetchRes)}