utils.ts
This file
Path
src/client/utils.ts
117 lines · 3.4 KiB · TypeScript
Last changed by
fix(client): skip an undefined entry inside a query array (#5272)Mahathir Mohammad Shuvobefore adoption2059584
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–19why, one step back1import type {2 ClientErrorStatusCode,3 ContentfulStatusCode,4 ServerErrorStatusCode,5} from '../utils/http-status'6import { fetchRP, DetailedError } from './fetch-result-please'7import type { ClientResponse, FilterClientResponseByStatusCode, ObjectType } from './types'89export { DetailedError }1011export const mergePath = (base: string, path: string) => {12 base = base.replace(/\/+$/, '')13 base = base + '/'14 path = path.replace(/^\/+/, '')15 return base + path16}1718export const replaceUrlParam = (urlString: string, params: Record<string, string | undefined>) => {19 for (const [k, v] of Object.entries(params)) {fix(client): replaceUrlParam should not match a param that prefixes another (#5096)Ishaan Samantraybefore adoption653025e
line 20why, one step back20 const reg = new RegExp('/:' + k + '(?:{[^/]+})?\\??(?=/|$)')fix(client): prevent URL corruption when replaceUrlParam contains $ replacement tokens (#5227)ADITYA KUMAR JHAbefore adoption4eb022d
line 21why, one step back21 urlString = urlString.replace(reg, () => (v ? `/${v}` : ''))Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 22–35why, one step back22 }23 return urlString24}2526export const buildSearchParams = (query: Record<string, string | string[]>) => {27 const searchParams = new URLSearchParams()2829 for (const [k, v] of Object.entries(query)) {30 if (v === undefined) {31 continue32 }3334 if (Array.isArray(v)) {35 for (const v2 of v) {fix(client): skip an undefined entry inside a query array (#5272)Mahathir Mohammad Shuvobefore adoption2059584
lines 36–38why, one step back36 if (v2 === undefined) {37 continue38 }Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 39–117why, one step back39 searchParams.append(k, v2)40 }41 } else {42 searchParams.set(k, v)43 }44 }4546 return searchParams47}4849export const replaceUrlProtocol = (urlString: string, protocol: 'ws' | 'http') => {50 switch (protocol) {51 case 'ws':52 return urlString.replace(/^http/, 'ws')53 case 'http':54 return urlString.replace(/^ws/, 'http')55 }56}5758export const removeIndexString = (urlString: string) => {59 if (/^https?:\/\/[^\/]+?\/index(?=\?|$)/.test(urlString)) {60 return urlString.replace(/\/index(?=\?|$)/, '/')61 }62 return urlString.replace(/\/index(?=\?|$)/, '')63}6465function isObject(item: unknown): item is ObjectType {66 return typeof item === 'object' && item !== null && !Array.isArray(item)67}6869export function deepMerge<T>(target: T, source: Record<string, unknown>): T {70 if (!isObject(target) && !isObject(source)) {71 return source as T72 }73 const merged = { ...target } as ObjectType<T>7475 for (const key in source) {76 const value = source[key]77 if (isObject(merged[key]) && isObject(value)) {78 merged[key] = deepMerge(merged[key], value)79 } else {80 merged[key] = value as T[keyof T] & T81 }82 }8384 return merged as T85}8687/**88 * Shortcut to get a consumable response from `hc`'s fetch calls (Response), with types inference.89 *90 * Smartly parse the response data, throwing a structured error if the response is not `ok`. ({@link DetailedError})91 *92 * @example const result = await parseResponse(client.posts.$get())93 */94// eslint-disable-next-line @typescript-eslint/no-explicit-any95export async function parseResponse<T extends ClientResponse<any>>(96 fetchRes: T | Promise<T>97): Promise<98 FilterClientResponseByStatusCode<99 T,100 Exclude<ContentfulStatusCode, ClientErrorStatusCode | ServerErrorStatusCode> // Filter out the error responses101 > extends never102 ? // Filtered responses does not include any contentful responses, exit with undefined103 undefined104 : // Filtered responses includes contentful responses, proceed to infer the type105 FilterClientResponseByStatusCode<106 T,107 Exclude<ContentfulStatusCode, ClientErrorStatusCode | ServerErrorStatusCode>108 > extends ClientResponse<infer RT, infer _, infer RF>109 ? RF extends 'json'110 ? RT111 : RT extends string112 ? RT113 : string114 : undefined115> {116 return fetchRP(fetchRes)117}