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
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–32why, one step back1import type { Hono } from '../hono'2import type { FormValue, ValidationTargets } from '../types'3import { serialize } from '../utils/cookie'4import type { UnionToIntersection } from '../utils/types'5import type { BuildSearchParamsFn, Callback, Client, ClientRequestOptions } from './types'6import {7 buildSearchParams,8 deepMerge,9 mergePath,10 removeIndexString,11 replaceUrlParam,12 replaceUrlProtocol,13} from './utils'1415const createProxy = (callback: Callback, path: string[]) => {16 const proxy: unknown = new Proxy(() => {}, {17 get(_obj, key) {18 if (typeof key !== 'string' || key === 'then') {19 return undefined20 }21 return createProxy(callback, [...path, key])22 },23 apply(_1, _2, args) {24 return callback({25 path,26 args,27 })28 },29 })30 return proxy31}32fix(client): omit empty query delimiter (#5283)Ersa Oktavian Ramadanbefore adoption73794bd
lines 33–37why, one step back33const appendQueryParams = (url: string, searchParams: URLSearchParams): string => {34 const queryString = searchParams.toString()35 return queryString ? `${url}?${queryString}` : url36}37Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 38–76why, one step back38class ClientRequestImpl {39 private url: string40 private method: string41 private buildSearchParams: BuildSearchParamsFn42 private queryParams: URLSearchParams | undefined = undefined43 private pathParams: Record<string, string> = {}44 private rBody: BodyInit | undefined45 private cType: string | undefined = undefined4647 constructor(48 url: string,49 method: string,50 options: {51 buildSearchParams: BuildSearchParamsFn52 }53 ) {54 this.url = url55 this.method = method56 this.buildSearchParams = options.buildSearchParams57 }58 fetch = async (59 args?: ValidationTargets<FormValue> & {60 param?: Record<string, string>61 },62 opt?: ClientRequestOptions63 ) => {64 if (args) {65 if (args.query) {66 this.queryParams = this.buildSearchParams(args.query)67 }6869 if (args.form) {70 const form = new FormData()71 for (const [k, v] of Object.entries(args.form)) {72 if (v === undefined) {73 continue74 }75 if (Array.isArray(v)) {76 for (const v2 of v) {fix(client): skip an undefined entry inside a form array (#5280)Yusuke Wadabefore adoptionc4a4407
lines 77–79why, one step back77 if (v2 === undefined) {78 continue79 }Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 80–88why, one step back80 form.append(k, v2)81 }82 } else {83 form.append(k, v)84 }85 }86 this.rBody = form87 }88fix(client): send falsy JSON bodies (#5215)Ersa Oktavian Ramadanbefore adoption329b6f4
line 89why, one step back89 if (args.json !== undefined) {Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 90–100why, one step back90 this.rBody = JSON.stringify(args.json)91 this.cType = 'application/json'92 }9394 if (args.param) {95 this.pathParams = args.param96 }97 }9899 let methodUpperCase = this.method.toUpperCase()100fix(client): skip undefined header and cookie values (#5244)Ersa Oktavian Ramadanbefore adoptiond6c0b0d
line 101why, one step back101 const headerValues: Record<string, string | undefined> = {Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 102–108why, one step back102 ...args?.header,103 ...(typeof opt?.headers === 'function' ? await opt.headers() : opt?.headers),104 }105106 if (args?.cookie) {107 const cookies: string[] = []108 for (const [key, value] of Object.entries(args.cookie)) {fix(client): skip undefined header and cookie values (#5244)Ersa Oktavian Ramadanbefore adoptiond6c0b0d
lines 109–111why, one step back109 if (value === undefined) {110 continue111 }fix(client): serialize multiple cookies correctly (#5202)Ersa Oktavian Ramadanbefore adoptionf2a72d3
line 112why, one step back112 cookies.push(serialize(key, value))Merge commit from forkYusuke Wadabefore adoptionf0b094d
line 113why, one step back113 }fix(client): skip undefined header and cookie values (#5244)Ersa Oktavian Ramadanbefore adoptiond6c0b0d
lines 114–116why, one step back114 if (cookies.length > 0) {115 headerValues['Cookie'] = cookies.join('; ')116 }Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 117–122why, one step back117 }118119 if (this.cType) {120 headerValues['Content-Type'] = this.cType121 }122fix(client): skip undefined header and cookie values (#5244)Ersa Oktavian Ramadanbefore adoptiond6c0b0d
lines 123–128why, one step back123 const headers = new Headers()124 for (const [key, value] of Object.entries(headerValues)) {125 if (value !== undefined) {126 headers.set(key, value)127 }128 }Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 129–134why, one step back129 let url = this.url130131 url = removeIndexString(url)132 url = replaceUrlParam(url, this.pathParams)133134 if (this.queryParams) {fix(client): omit empty query delimiter (#5283)Ersa Oktavian Ramadanbefore adoption73794bd
line 135why, one step back135 url = appendQueryParams(url, this.queryParams)Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 136–189why, one step back136 }137 methodUpperCase = this.method.toUpperCase()138 const setBody = !(methodUpperCase === 'GET' || methodUpperCase === 'HEAD')139140 // Pass URL string to 1st arg for testing with MSW and node-fetch141 return (opt?.fetch || fetch)(url, {142 body: setBody ? this.rBody : undefined,143 method: methodUpperCase,144 headers: headers,145 ...opt?.init,146 })147 }148}149150// eslint-disable-next-line @typescript-eslint/no-explicit-any151export const hc = <T extends Hono<any, any, any>, Prefix extends string = string>(152 baseUrl: Prefix,153 options?: ClientRequestOptions154) =>155 createProxy(function proxyCallback(opts) {156 const buildSearchParamsOption = options?.buildSearchParams ?? buildSearchParams157 const parts = [...opts.path]158 const lastParts = parts.slice(-3).reverse()159160 // allow calling .toString() and .valueOf() on the proxy161 if (lastParts[0] === 'toString') {162 if (lastParts[1] === 'name') {163 // e.g. hc().somePath.name.toString() -> "somePath"164 return lastParts[2] || ''165 }166 // e.g. hc().somePath.toString()167 return proxyCallback.toString()168 }169170 if (lastParts[0] === 'valueOf') {171 if (lastParts[1] === 'name') {172 // e.g. hc().somePath.name.valueOf() -> "somePath"173 return lastParts[2] || ''174 }175 // e.g. hc().somePath.valueOf()176 return proxyCallback177 }178179 let method = ''180 if (/^\$/.test(lastParts[0] as string)) {181 const last = parts.pop()182 if (last) {183 method = last.replace(/^\$/, '')184 }185 }186187 const path = parts.join('/')188 const url = mergePath(baseUrl, path)189 if (method === 'url' || method === 'path') {fix(client): keep a param value of "index" in $url() and $path() (#5297)Mahathir Mohammad Shuvobefore adoption50b8788
lines 190–192why, one step back190 // Strip the synthetic `index` segment before substituting params, so that a param191 // whose value is `index` is not mistaken for one.192 let result = removeIndexString(url)Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 193–194why, one step back193 if (opts.args[0]) {194 if (opts.args[0].param) {fix(client): keep a param value of "index" in $url() and $path() (#5297)Mahathir Mohammad Shuvobefore adoption50b8788
line 195why, one step back195 result = replaceUrlParam(result, opts.args[0].param)Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 196–197why, one step back196 }197 if (opts.args[0].query) {fix(client): omit empty query delimiter (#5283)Ersa Oktavian Ramadanbefore adoption73794bd
line 198why, one step back198 result = appendQueryParams(result, buildSearchParamsOption(opts.args[0].query))Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 199–206why, one step back199 }200 }201 if (method === 'url') {202 return new URL(result)203 }204 return result.slice(baseUrl.replace(/\/+$/, '').length).replace(/^\/?/, '/')205 }206 if (method === 'ws') {fix(client): normalize root WebSocket URLs (#5291)Ersa Oktavian Ramadanbefore adoption499c35e
line 207why, one step back207 const normalizedUrl = removeIndexString(url)Merge commit from forkYusuke Wadabefore adoptionf0b094d
line 208why, one step back208 const webSocketUrl = replaceUrlProtocol(fix(client): normalize root WebSocket URLs (#5291)Ersa Oktavian Ramadanbefore adoption499c35e
line 209why, one step back209 opts.args[0]?.param ? replaceUrlParam(normalizedUrl, opts.args[0].param) : normalizedUrl,Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 210–215why, one step back210 'ws'211 )212 const targetUrl = new URL(webSocketUrl)213214 const queryParams: Record<string, string | string[]> | undefined = opts.args[0]?.query215 if (queryParams) {fix(client): support custom buildSearchParams and filter undefined query in $ws() (#5256)ADITYA KUMAR JHAbefore adoption1096d66
lines 216–218why, one step back216 const searchParams = buildSearchParamsOption(queryParams)217 searchParams.forEach((value, key) => {218 targetUrl.searchParams.append(key, value)Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 219–235why, one step back219 })220 }221 const establishWebSocket = (...args: ConstructorParameters<typeof WebSocket>) => {222 if (options?.webSocket !== undefined && typeof options.webSocket === 'function') {223 return options.webSocket(...args)224 }225 return new WebSocket(...args)226 }227228 return establishWebSocket(targetUrl.toString())229 }230231 const req = new ClientRequestImpl(url, method, {232 buildSearchParams: buildSearchParamsOption,233 })234 if (method) {235 options ??= {}fix(client): merge function headers with per-request headers (#5092)Yusuke Wadabefore adoptionf999209
lines 236–245why, one step back236 const reqOptions: ClientRequestOptions = { ...opts.args[1] }237 const baseHeaders = options.headers238 const reqHeaders = reqOptions.headers239 if (baseHeaders && reqHeaders) {240 reqOptions.headers = async () => ({241 ...(typeof baseHeaders === 'function' ? await baseHeaders() : baseHeaders),242 ...(typeof reqHeaders === 'function' ? await reqHeaders() : reqHeaders),243 })244 }245 const args = deepMerge<ClientRequestOptions>(options, reqOptions)Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 246–249why, one step back246 return req.fetch(opts.args[0], args)247 }248 return req249 }, []) as UnionToIntersection<Client<T, Prefix>>