/** * RequestCredentials */ export type RequestCredentials = 'omit' | 'same-origin' | 'include' /** * Subset of FetchRequestConfig */ export type RequestConfig = { baseURL?: string url?: string method?: 'GET' | 'PUT' | 'PATCH' | 'POST' | 'DELETE' | 'OPTIONS' | 'HEAD' params?: unknown data?: TData | FormData responseType?: 'arraybuffer' | 'blob' | 'document' | 'json' | 'text' | 'stream' signal?: AbortSignal headers?: [string, string][] | Record credentials?: RequestCredentials } /** * Subset of FetchResponse */ export type ResponseConfig = { data: TData status: number statusText: string headers: Headers } let _config: Partial = {} export const getConfig = () => _config export const setConfig = (config: Partial) => { _config = config return getConfig() } export const mergeConfig = (...configs: Array>): Partial => { return configs.reduce>((merged, config) => { return { ...merged, ...config, headers: { ...(Array.isArray(merged.headers) ? Object.fromEntries(merged.headers) : merged.headers), ...(Array.isArray(config.headers) ? Object.fromEntries(config.headers) : config.headers), }, } }, {}) } export type ResponseErrorConfig = TError export type Client = (config: RequestConfig) => Promise> export const client = async ( paramsConfig: RequestConfig, ): Promise> => { const normalizedParams = new URLSearchParams() const config = mergeConfig(getConfig(), paramsConfig) Object.entries(config.params || {}).forEach(([key, value]) => { if (value !== undefined) { normalizedParams.append(key, value === null ? 'null' : value.toString()) } }) let targetUrl = [config.baseURL, config.url].filter(Boolean).join('') if (config.params) { targetUrl += `?${normalizedParams}` } const response = await fetch(targetUrl, { credentials: config.credentials || 'same-origin', method: config.method?.toUpperCase(), body: config.data instanceof FormData ? config.data : JSON.stringify(config.data), signal: config.signal, headers: config.headers, }) const data = [204, 205, 304].includes(response.status) || !response.body ? {} : await response.json() return { data: data as TResponseData, status: response.status, statusText: response.statusText, headers: response.headers as Headers, } } client.getConfig = getConfig client.setConfig = setConfig export default client