0
0
mirror of https://github.com/honojs/hono.git synced 2024-11-25 13:19:30 +01:00
hono/src/client/utils.ts

55 lines
1.5 KiB
TypeScript

import type { ObjectType } from './types'
export const mergePath = (base: string, path: string) => {
base = base.replace(/\/+$/, '')
base = base + '/'
path = path.replace(/^\/+/, '')
return base + path
}
export const replaceUrlParam = (urlString: string, params: Record<string, string | undefined>) => {
for (const [k, v] of Object.entries(params)) {
const reg = new RegExp('/:' + k + '(?:{[^/]+})?\\??')
urlString = urlString.replace(reg, v ? `/${v}` : '')
}
return urlString
}
export const replaceUrlProtocol = (urlString: string, protocol: 'ws' | 'http') => {
switch (protocol) {
case 'ws':
return urlString.replace(/^http/, 'ws')
case 'http':
return urlString.replace(/^ws/, 'http')
}
}
export const removeIndexString = (urlSting: string) => {
if (/^https?:\/\/[^\/]+?\/index$/.test(urlSting)) {
return urlSting.replace(/\/index$/, '/')
}
return urlSting.replace(/\/index$/, '')
}
function isObject(item: unknown): item is ObjectType {
return typeof item === 'object' && item !== null && !Array.isArray(item)
}
export function deepMerge<T>(target: T, source: Record<string, unknown>): T {
if (!isObject(target) && !isObject(source)) {
return source as T
}
const merged = { ...target } as ObjectType<T>
for (const key in source) {
const value = source[key]
if (isObject(merged[key]) && isObject(value)) {
merged[key] = deepMerge(merged[key], value)
} else {
merged[key] = value as T[keyof T] & T
}
}
return merged as T
}