fetch-result-please.ts
This file
Path
src/client/fetch-result-please.ts
95 lines · 2.6 KiB · TypeScript
Last changed by
Not known.
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–95why, one step back1/**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 & {16 _data: any17 /**18 * @description BodyInit property from whatwg-fetch polyfill19 *20 * @link https://github.com/JakeChampion/fetch/blob/main/fetch.js#L23821 */22 _bodyInit?: any23 }2425 const hasBody =26 (_fetchRes.body || _fetchRes._bodyInit) && !nullBodyResponses.has(_fetchRes.status)2728 if (hasBody) {29 const responseType = detectResponseType(_fetchRes)30 _fetchRes._data = await _fetchRes[responseType]()31 }3233 if (!_fetchRes.ok) {34 throw new DetailedError(`${_fetchRes.status} ${_fetchRes.statusText}`, {35 statusCode: _fetchRes?.status,36 detail: {37 data: _fetchRes?._data,38 statusText: _fetchRes?.statusText,39 },40 })41 }4243 return _fetchRes._data44}4546export class DetailedError extends Error {47 /**48 * Additional `message` that will be logged AND returned to client49 */50 public detail?: any51 /**52 * Additional `code` that will be logged AND returned to client53 */54 public code?: any55 /**56 * Additional value that will be logged AND NOT returned to client57 */58 public log?: any59 /**60 * Optionally set the status code to return, in a web server context61 */62 public statusCode?: any6364 constructor(65 message: string,66 options: { detail?: any; code?: any; statusCode?: number; log?: any } = {}67 ) {68 super(message)69 this.name = 'DetailedError'70 this.log = options.log71 this.detail = options.detail72 this.code = options.code73 this.statusCode = options.statusCode74 }75}7677// This is used to match the content-type header for 'json'78const jsonRegex = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(?:;.+)?$/i7980function detectResponseType(response: Response): 'json' | 'text' {81 const _contentType = response.headers.get('content-type')8283 if (!_contentType) {84 return 'text'85 }8687 // `_contentType` might look like: `application/json; charset=utf-8`, `text/plain`, so we get the first part before `;`88 const contentType = _contentType.split(';').shift()!8990 if (jsonRegex.test(contentType)) {91 return 'json'92 }9394 return 'text'95}