Skip to content
Myr

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` ---------

authored by Trung Dang · committed by GitHub · parent 0839066 · Browse files · 4 files+212 added−1 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: Yusuke Wada <yusuke@kamawada.com>

Diff stats

4 files+212 added−1 removed

  • tests:+100 added−0 removed
  • other:+112 added−1 removed

4 files+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 */67const nullBodyResponses = new Set([101, 204, 205, 304])89/**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 */14export async function fetchRP(fetchRes: Response | Promise<Response>): Promise<any> {15 const _fetchRes = (await fetchRes) as unknown as Response & { _data: any }1617 const hasBody = _fetchRes.body && !nullBodyResponses.has(_fetchRes.status)1819 if (hasBody) {20 const responseType = detectResponseType(_fetchRes)21 _fetchRes._data = await _fetchRes[responseType]()22 }2324 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 }3334 return _fetchRes._data35}3637export 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?: any5455 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}6667// This is used to match the content-type header for 'json'68const jsonRegex = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(?:;.+)?$/i6970function detectResponseType(response: Response): 'json' | 'text' {71 const _contentType = response.headers.get('content-type')7273 if (!_contentType) {74 return 'text'75 }7677 // `_contentType` might look like: `application/json; charset=utf-8`, `text/plain`, so we get the first part before `;`78 const contentType = _contentType.split(';').shift()!7980 if (jsonRegex.test(contentType)) {81 return 'json'82 }8384 return 'text'85}
modified:src/client/index.ts+1 added
modified:src/client/utils.test.ts+100 added
1import { HttpResponse, http } from 'msw'2import { setupServer } from 'msw/node'3import { Hono } from '../hono'4import type { Expect, Equal } from '../utils/types'5import { hc } from './client'6import {7 buildSearchParams,8 deepMerge,9 parseResponse,10 mergePath,11 removeIndexString,12 replaceUrlParam,13 replaceUrlProtocol,
130 unmodified lines
144 timeout: 2,145 })146 })147})148149describe('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 })166167 const client = hc<typeof app>('http://localhost')168169 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 )201202 beforeAll(() => server.listen())203 afterEach(() => server.resetHandlers())204 afterAll(() => server.close())205206 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