utils.ts
This file
Path
src/client/utils.ts
74 lines · 1.9 KiB · TypeScript
Last changed by
fix(client): return query params in $url (#3541)Alex Groverbefore adoption3d8abbc
History of this fileTake it
The walk stopped after 200 commits: lines older than 7ee829b point at it.
v4.4.7Yusuke Wadabefore adoption7ee829b
lines 1–9why, one step back1import type { ObjectType } from './types'23export const mergePath = (base: string, path: string) => {4 base = base.replace(/\/+$/, '')5 base = base + '/'6 path = path.replace(/^\/+/, '')7 return base + path8}9fix(client): replace optional params to url correctly (#3304)Yusuke Wadabefore adoption331b3d8
line 10why, one step back10export const replaceUrlParam = (urlString: string, params: Record<string, string | undefined>) => {v4.4.7Yusuke Wadabefore adoption7ee829b
line 11why, one step back11 for (const [k, v] of Object.entries(params)) {fix(client): replace optional params to url correctly (#3304)Yusuke Wadabefore adoption331b3d8
lines 12–13why, one step back12 const reg = new RegExp('/:' + k + '(?:{[^/]+})?\\??')13 urlString = urlString.replace(reg, v ? `/${v}` : '')v4.4.7Yusuke Wadabefore adoption7ee829b
lines 14–17why, one step back14 }15 return urlString16}17fix(client): return query params in $url (#3541)Alex Groverbefore adoption3d8abbc
lines 18–37why, one step back18export const buildSearchParams = (query: Record<string, string | string[]>) => {19 const searchParams = new URLSearchParams()2021 for (const [k, v] of Object.entries(query)) {22 if (v === undefined) {23 continue24 }2526 if (Array.isArray(v)) {27 for (const v2 of v) {28 searchParams.append(k, v2)29 }30 } else {31 searchParams.set(k, v)32 }33 }3435 return searchParams36}37v4.4.7Yusuke Wadabefore adoption7ee829b
lines 38–74why, one step back38export const replaceUrlProtocol = (urlString: string, protocol: 'ws' | 'http') => {39 switch (protocol) {40 case 'ws':41 return urlString.replace(/^http/, 'ws')42 case 'http':43 return urlString.replace(/^ws/, 'http')44 }45}4647export const removeIndexString = (urlSting: string) => {48 if (/^https?:\/\/[^\/]+?\/index$/.test(urlSting)) {49 return urlSting.replace(/\/index$/, '/')50 }51 return urlSting.replace(/\/index$/, '')52}5354function isObject(item: unknown): item is ObjectType {55 return typeof item === 'object' && item !== null && !Array.isArray(item)56}5758export function deepMerge<T>(target: T, source: Record<string, unknown>): T {59 if (!isObject(target) && !isObject(source)) {60 return source as T61 }62 const merged = { ...target } as ObjectType<T>6364 for (const key in source) {65 const value = source[key]66 if (isObject(merged[key]) && isObject(value)) {67 merged[key] = deepMerge(merged[key], value)68 } else {69 merged[key] = value as T[keyof T] & T70 }71 }7273 return merged as T74}