client.ts
This file
Path
src/client/client.ts
249 lines 路 7.3 KiB 路 TypeScript
Last changed by
fix(client): normalize root WebSocket URLs (#5291)Ersa Oktavian Ramadanbefore adoption499c35e
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250import type { Hono } from '../hono'import type { FormValue, ValidationTargets } from '../types'import { serialize } from '../utils/cookie'import type { UnionToIntersection } from '../utils/types'import type { BuildSearchParamsFn, Callback, Client, ClientRequestOptions } from './types'import { buildSearchParams, deepMerge, mergePath, removeIndexString, replaceUrlParam, replaceUrlProtocol,} from './utils'
const createProxy = (callback: Callback, path: string[]) => { const proxy: unknown = new Proxy(() => {}, { get(_obj, key) { if (typeof key !== 'string' || key === 'then') { return undefined } return createProxy(callback, [...path, key]) }, apply(_1, _2, args) { return callback({ path, args, }) }, }) return proxy}
const appendQueryParams = (url: string, searchParams: URLSearchParams): string => { const queryString = searchParams.toString() return queryString ? `${url}?${queryString}` : url}
class ClientRequestImpl { private url: string private method: string private buildSearchParams: BuildSearchParamsFn private queryParams: URLSearchParams | undefined = undefined private pathParams: Record<string, string> = {} private rBody: BodyInit | undefined private cType: string | undefined = undefined
constructor( url: string, method: string, options: { buildSearchParams: BuildSearchParamsFn } ) { this.url = url this.method = method this.buildSearchParams = options.buildSearchParams } fetch = async ( args?: ValidationTargets<FormValue> & { param?: Record<string, string> }, opt?: ClientRequestOptions ) => { if (args) { if (args.query) { this.queryParams = this.buildSearchParams(args.query) }
if (args.form) { const form = new FormData() for (const [k, v] of Object.entries(args.form)) { if (v === undefined) { continue } if (Array.isArray(v)) { for (const v2 of v) { if (v2 === undefined) { continue } form.append(k, v2) } } else { form.append(k, v) } } this.rBody = form }
if (args.json !== undefined) { this.rBody = JSON.stringify(args.json) this.cType = 'application/json' }
if (args.param) { this.pathParams = args.param } }
let methodUpperCase = this.method.toUpperCase()
const headerValues: Record<string, string | undefined> = { ...args?.header, ...(typeof opt?.headers === 'function' ? await opt.headers() : opt?.headers), }
if (args?.cookie) { const cookies: string[] = [] for (const [key, value] of Object.entries(args.cookie)) { if (value === undefined) { continue } cookies.push(serialize(key, value)) } if (cookies.length > 0) { headerValues['Cookie'] = cookies.join('; ') } }
if (this.cType) { headerValues['Content-Type'] = this.cType }
const headers = new Headers() for (const [key, value] of Object.entries(headerValues)) { if (value !== undefined) { headers.set(key, value) } } let url = this.url
url = removeIndexString(url) url = replaceUrlParam(url, this.pathParams)
if (this.queryParams) { url = appendQueryParams(url, this.queryParams) } methodUpperCase = this.method.toUpperCase() const setBody = !(methodUpperCase === 'GET' || methodUpperCase === 'HEAD')
// Pass URL string to 1st arg for testing with MSW and node-fetch return (opt?.fetch || fetch)(url, { body: setBody ? this.rBody : undefined, method: methodUpperCase, headers: headers, ...opt?.init, }) }}
// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const hc = <T extends Hono<any, any, any>, Prefix extends string = string>( baseUrl: Prefix, options?: ClientRequestOptions) => createProxy(function proxyCallback(opts) { const buildSearchParamsOption = options?.buildSearchParams ?? buildSearchParams const parts = [...opts.path] const lastParts = parts.slice(-3).reverse()
// allow calling .toString() and .valueOf() on the proxy if (lastParts[0] === 'toString') { if (lastParts[1] === 'name') { // e.g. hc().somePath.name.toString() -> "somePath" return lastParts[2] || '' } // e.g. hc().somePath.toString() return proxyCallback.toString() }
if (lastParts[0] === 'valueOf') { if (lastParts[1] === 'name') { // e.g. hc().somePath.name.valueOf() -> "somePath" return lastParts[2] || '' } // e.g. hc().somePath.valueOf() return proxyCallback }
let method = '' if (/^\$/.test(lastParts[0] as string)) { const last = parts.pop() if (last) { method = last.replace(/^\$/, '') } }
const path = parts.join('/') const url = mergePath(baseUrl, path) if (method === 'url' || method === 'path') { // Strip the synthetic `index` segment before substituting params, so that a param // whose value is `index` is not mistaken for one. let result = removeIndexString(url) if (opts.args[0]) { if (opts.args[0].param) { result = replaceUrlParam(result, opts.args[0].param) } if (opts.args[0].query) { result = appendQueryParams(result, buildSearchParamsOption(opts.args[0].query)) } } if (method === 'url') { return new URL(result) } return result.slice(baseUrl.replace(/\/+$/, '').length).replace(/^\/?/, '/') } if (method === 'ws') { const normalizedUrl = removeIndexString(url) const webSocketUrl = replaceUrlProtocol( opts.args[0]?.param ? replaceUrlParam(normalizedUrl, opts.args[0].param) : normalizedUrl, 'ws' ) const targetUrl = new URL(webSocketUrl)
const queryParams: Record<string, string | string[]> | undefined = opts.args[0]?.query if (queryParams) { const searchParams = buildSearchParamsOption(queryParams) searchParams.forEach((value, key) => { targetUrl.searchParams.append(key, value) }) } const establishWebSocket = (...args: ConstructorParameters<typeof WebSocket>) => { if (options?.webSocket !== undefined && typeof options.webSocket === 'function') { return options.webSocket(...args) } return new WebSocket(...args) }
return establishWebSocket(targetUrl.toString()) }
const req = new ClientRequestImpl(url, method, { buildSearchParams: buildSearchParamsOption, }) if (method) { options ??= {} const reqOptions: ClientRequestOptions = { ...opts.args[1] } const baseHeaders = options.headers const reqHeaders = reqOptions.headers if (baseHeaders && reqHeaders) { reqOptions.headers = async () => ({ ...(typeof baseHeaders === 'function' ? await baseHeaders() : baseHeaders), ...(typeof reqHeaders === 'function' ? await reqHeaders() : reqHeaders), }) } const args = deepMerge<ClientRequestOptions>(options, reqOptions) return req.fetch(opts.args[0], args) } return req }, []) as UnionToIntersection<Client<T, Prefix>>