client.ts
This file
Path
src/client/client.ts
223 lines · 6.3 KiB · TypeScript
Last changed by
Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
History of this fileTake it
The walk stopped after 200 commits: lines older than 793ffda point at it.
chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 1–4why, one step back1import type { Hono } from '../hono'2import type { FormValue, ValidationTargets } from '../types'3import { serialize } from '../utils/cookie'4import type { UnionToIntersection } from '../utils/types'Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
line 5why, one step back5import type { BuildSearchParamsFn, Callback, Client, ClientRequestOptions } from './types'chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 6–35why, one step back6import {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}3233class ClientRequestImpl {34 private url: string35 private method: stringMerge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
line 36why, one step back36 private buildSearchParams: BuildSearchParamsFnchore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 37–41why, one step back37 private queryParams: URLSearchParams | undefined = undefined38 private pathParams: Record<string, string> = {}39 private rBody: BodyInit | undefined40 private cType: string | undefined = undefined41Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
lines 42–48why, one step back42 constructor(43 url: string,44 method: string,45 options: {46 buildSearchParams: BuildSearchParamsFn47 }48 ) {chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 49–50why, one step back49 this.url = url50 this.method = methodMerge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
line 51why, one step back51 this.buildSearchParams = options.buildSearchParamschore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 52–60why, one step back52 }53 fetch = async (54 args?: ValidationTargets<FormValue> & {55 param?: Record<string, string>56 },57 opt?: ClientRequestOptions58 ) => {59 if (args) {60 if (args.query) {Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
line 61why, one step back61 this.queryParams = this.buildSearchParams(args.query)chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 62–66why, one step back62 }6364 if (args.form) {65 const form = new FormData()66 for (const [k, v] of Object.entries(args.form)) {fix(client): skip undefined values in form data serialization (#4732)Aiden Liubefore adoption67ac19a
lines 67–69why, one step back67 if (v === undefined) {68 continue69 }chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 70–132why, one step back70 if (Array.isArray(v)) {71 for (const v2 of v) {72 form.append(k, v2)73 }74 } else {75 form.append(k, v)76 }77 }78 this.rBody = form79 }8081 if (args.json) {82 this.rBody = JSON.stringify(args.json)83 this.cType = 'application/json'84 }8586 if (args.param) {87 this.pathParams = args.param88 }89 }9091 let methodUpperCase = this.method.toUpperCase()9293 const headerValues: Record<string, string> = {94 ...args?.header,95 ...(typeof opt?.headers === 'function' ? await opt.headers() : opt?.headers),96 }9798 if (args?.cookie) {99 const cookies: string[] = []100 for (const [key, value] of Object.entries(args.cookie)) {101 cookies.push(serialize(key, value, { path: '/' }))102 }103 headerValues['Cookie'] = cookies.join(',')104 }105106 if (this.cType) {107 headerValues['Content-Type'] = this.cType108 }109110 const headers = new Headers(headerValues ?? undefined)111 let url = this.url112113 url = removeIndexString(url)114 url = replaceUrlParam(url, this.pathParams)115116 if (this.queryParams) {117 url = url + '?' + this.queryParams.toString()118 }119 methodUpperCase = this.method.toUpperCase()120 const setBody = !(methodUpperCase === 'GET' || methodUpperCase === 'HEAD')121122 // Pass URL string to 1st arg for testing with MSW and node-fetch123 return (opt?.fetch || fetch)(url, {124 body: setBody ? this.rBody : undefined,125 method: methodUpperCase,126 headers: headers,127 ...opt?.init,128 })129 }130}131132// eslint-disable-next-line @typescript-eslint/no-explicit-anyMerge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
lines 133–134why, one step back133export const hc = <T extends Hono<any, any, any>, Prefix extends string = string>(134 baseUrl: Prefix,chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 135–137why, one step back135 options?: ClientRequestOptions136) =>137 createProxy(function proxyCallback(opts) {Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
line 138why, one step back138 const buildSearchParamsOption = options?.buildSearchParams ?? buildSearchParamschore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 139–170why, one step back139 const parts = [...opts.path]140 const lastParts = parts.slice(-3).reverse()141142 // allow calling .toString() and .valueOf() on the proxy143 if (lastParts[0] === 'toString') {144 if (lastParts[1] === 'name') {145 // e.g. hc().somePath.name.toString() -> "somePath"146 return lastParts[2] || ''147 }148 // e.g. hc().somePath.toString()149 return proxyCallback.toString()150 }151152 if (lastParts[0] === 'valueOf') {153 if (lastParts[1] === 'name') {154 // e.g. hc().somePath.name.valueOf() -> "somePath"155 return lastParts[2] || ''156 }157 // e.g. hc().somePath.valueOf()158 return proxyCallback159 }160161 let method = ''162 if (/^\$/.test(lastParts[0] as string)) {163 const last = parts.pop()164 if (last) {165 method = last.replace(/^\$/, '')166 }167 }168169 const path = parts.join('/')170 const url = mergePath(baseUrl, path)Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
line 171why, one step back171 if (method === 'url' || method === 'path') {chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 172–177why, one step back172 let result = url173 if (opts.args[0]) {174 if (opts.args[0].param) {175 result = replaceUrlParam(url, opts.args[0].param)176 }177 if (opts.args[0].query) {Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
line 178why, one step back178 result = result + '?' + buildSearchParamsOption(opts.args[0].query).toString()chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 179–181why, one step back179 }180 }181 result = removeIndexString(result)Merge pull request #4735 from honojs/nextYusuke Wadabefore adoption01e78ad
lines 182–185why, one step back182 if (method === 'url') {183 return new URL(result)184 }185 return result.slice(baseUrl.replace(/\/+$/, '').length).replace(/^\/?/, '/')chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 186–213why, one step back186 }187 if (method === 'ws') {188 const webSocketUrl = replaceUrlProtocol(189 opts.args[0] && opts.args[0].param ? replaceUrlParam(url, opts.args[0].param) : url,190 'ws'191 )192 const targetUrl = new URL(webSocketUrl)193194 const queryParams: Record<string, string | string[]> | undefined = opts.args[0]?.query195 if (queryParams) {196 Object.entries(queryParams).forEach(([key, value]) => {197 if (Array.isArray(value)) {198 value.forEach((item) => targetUrl.searchParams.append(key, item))199 } else {200 targetUrl.searchParams.set(key, value)201 }202 })203 }204 const establishWebSocket = (...args: ConstructorParameters<typeof WebSocket>) => {205 if (options?.webSocket !== undefined && typeof options.webSocket === 'function') {206 return options.webSocket(...args)207 }208 return new WebSocket(...args)209 }210211 return establishWebSocket(targetUrl.toString())212 }213Merge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
lines 214–216why, one step back214 const req = new ClientRequestImpl(url, method, {215 buildSearchParams: buildSearchParamsOption,216 })chore: enable `skipLibCheck` to resolve TypeScript compilation issues (#4342)Yusuke Wadabefore adoption793ffda
lines 217–222why, one step back217 if (method) {218 options ??= {}219 const args = deepMerge<ClientRequestOptions>(options, { ...opts.args[1] })220 return req.fetch(opts.args[0], args)221 }222 return reqMerge pull request #4574 from honojs/nextYusuke Wadabefore adoption0d739b6
line 223why, one step back223 }, []) as UnionToIntersection<Client<T, Prefix>>