|
| 1 | +import { FetchError, FetchResponse, RequestConfig } from './FetchClientTypes'; |
| 2 | +import { createFormattedError } from './FetchInterceptor'; |
| 3 | + |
| 4 | +/** |
| 5 | + * Build URL with query parameters |
| 6 | + * @param baseURL Base URL |
| 7 | + * @param url Endpoint URL |
| 8 | + * @param params Query parameters |
| 9 | + * @returns Complete URL with query parameters |
| 10 | + */ |
| 11 | +const buildURL = (baseURL: string, url: string, params?: Record<string, string | number | boolean>): string => { |
| 12 | + const fullURL = url.startsWith('http') ? url : `${baseURL}${url}`; |
| 13 | + |
| 14 | + if (!params) return fullURL; |
| 15 | + |
| 16 | + const urlObj = new URL(fullURL); |
| 17 | + Object.entries(params).forEach(([key, value]) => { |
| 18 | + if (value !== undefined && value !== null) { |
| 19 | + urlObj.searchParams.append(key, String(value)); |
| 20 | + } |
| 21 | + }); |
| 22 | + |
| 23 | + return urlObj.toString(); |
| 24 | +}; |
| 25 | + |
| 26 | +/** |
| 27 | + * Parse response data based on content type |
| 28 | + * @param response Fetch response |
| 29 | + * @returns Parsed data |
| 30 | + */ |
| 31 | +const parseResponseData = async (response: Response): Promise<unknown> => { |
| 32 | + const contentType = response.headers.get('content-type'); |
| 33 | + |
| 34 | + if (contentType?.includes('application/json')) { |
| 35 | + return await response.json(); |
| 36 | + } else if (contentType?.includes('text/')) { |
| 37 | + return await response.text(); |
| 38 | + } else { |
| 39 | + return await response.blob(); |
| 40 | + } |
| 41 | +}; |
| 42 | + |
| 43 | +/** |
| 44 | + * Reusable fetch client class |
| 45 | + * |
| 46 | + * @author Pavan Kumar Jadda |
| 47 | + * @since 0.2.19 |
| 48 | + */ |
| 49 | +class FetchInstance { |
| 50 | + private readonly baseURL: string; |
| 51 | + private requestInterceptors: Array<(config: RequestConfig) => RequestConfig | Promise<RequestConfig>> = []; |
| 52 | + private responseInterceptors: Array<(response: FetchResponse<unknown>) => FetchResponse<unknown> | Promise<FetchResponse<unknown>>> = []; |
| 53 | + private errorInterceptors: Array<(error: FetchError) => FetchError | Promise<FetchError> | void | Promise<void>> = []; |
| 54 | + /** |
| 55 | + * Add request interceptor |
| 56 | + */ |
| 57 | + interceptors = { |
| 58 | + request: { |
| 59 | + use: (interceptor: (config: RequestConfig) => RequestConfig | Promise<RequestConfig>) => { |
| 60 | + this.requestInterceptors.push(interceptor); |
| 61 | + }, |
| 62 | + }, |
| 63 | + response: { |
| 64 | + use: ( |
| 65 | + successInterceptor?: (response: FetchResponse<unknown>) => FetchResponse<unknown> | Promise<FetchResponse<unknown>>, |
| 66 | + errorInterceptor?: (error: FetchError) => FetchError | Promise<FetchError> | void | Promise<void> |
| 67 | + ) => { |
| 68 | + if (successInterceptor) { |
| 69 | + this.responseInterceptors.push(successInterceptor); |
| 70 | + } |
| 71 | + if (errorInterceptor) { |
| 72 | + this.errorInterceptors.push(errorInterceptor); |
| 73 | + } |
| 74 | + }, |
| 75 | + }, |
| 76 | + }; |
| 77 | + |
| 78 | + constructor(baseURL: string = import.meta.env.VITE_REACT_APP_BASE_URL) { |
| 79 | + this.baseURL = baseURL; |
| 80 | + } |
| 81 | + |
| 82 | + /** |
| 83 | + * GET request |
| 84 | + */ |
| 85 | + async get<T = unknown>(url: string, config?: Omit<RequestConfig, 'method' | 'url'>): Promise<FetchResponse<T>> { |
| 86 | + return this.executeRequest({ ...config, method: 'GET', url }); |
| 87 | + } |
| 88 | + |
| 89 | + /** |
| 90 | + * POST request |
| 91 | + */ |
| 92 | + async post<T = unknown>(url: string, data?: unknown, config?: Omit<RequestConfig, 'method' | 'url' | 'body'>): Promise<FetchResponse<T>> { |
| 93 | + const body = data ? JSON.stringify(data) : undefined; |
| 94 | + return this.executeRequest({ ...config, method: 'POST', url, body }); |
| 95 | + } |
| 96 | + |
| 97 | + /** |
| 98 | + * PUT request |
| 99 | + */ |
| 100 | + async put<T = unknown>(url: string, data?: unknown, config?: Omit<RequestConfig, 'method' | 'url' | 'body'>): Promise<FetchResponse<T>> { |
| 101 | + const body = data ? JSON.stringify(data) : undefined; |
| 102 | + return this.executeRequest({ ...config, method: 'PUT', url, body }); |
| 103 | + } |
| 104 | + |
| 105 | + /** |
| 106 | + * DELETE request |
| 107 | + */ |
| 108 | + async delete<T = unknown>(url: string, config?: Omit<RequestConfig, 'method' | 'url'>): Promise<FetchResponse<T>> { |
| 109 | + return this.executeRequest({ ...config, method: 'DELETE', url }); |
| 110 | + } |
| 111 | + |
| 112 | + /** |
| 113 | + * PATCH request |
| 114 | + */ |
| 115 | + async patch<T = unknown>( |
| 116 | + url: string, |
| 117 | + data?: unknown, |
| 118 | + config?: Omit<RequestConfig, 'method' | 'url' | 'body'> |
| 119 | + ): Promise<FetchResponse<T>> { |
| 120 | + const body = data ? JSON.stringify(data) : undefined; |
| 121 | + return this.executeRequest<T>({ ...config, method: 'PATCH', url, body }); |
| 122 | + } |
| 123 | + |
| 124 | + /** |
| 125 | + * Generic request method |
| 126 | + */ |
| 127 | + async request<T = unknown>(config: RequestConfig): Promise<FetchResponse<T>> { |
| 128 | + return this.executeRequest(config); |
| 129 | + } |
| 130 | + |
| 131 | + /** |
| 132 | + * Execute request with interceptors |
| 133 | + */ |
| 134 | + private async executeRequest<T>(config: RequestConfig): Promise<FetchResponse<T>> { |
| 135 | + // Apply request interceptors |
| 136 | + let processedConfig = config; |
| 137 | + for (const interceptor of this.requestInterceptors) { |
| 138 | + processedConfig = await interceptor(processedConfig); |
| 139 | + } |
| 140 | + |
| 141 | + const { url, params, ...fetchConfig } = processedConfig; |
| 142 | + const fullURL = buildURL(this.baseURL, url || '', params); |
| 143 | + |
| 144 | + try { |
| 145 | + const response = await fetch(fullURL, fetchConfig); |
| 146 | + const data = await parseResponseData(response); |
| 147 | + |
| 148 | + const fetchResponse: FetchResponse<T> = { |
| 149 | + data: data as T, |
| 150 | + status: response.status, |
| 151 | + statusText: response.statusText, |
| 152 | + headers: response.headers, |
| 153 | + config: processedConfig, |
| 154 | + }; |
| 155 | + |
| 156 | + // Apply response interceptors |
| 157 | + let processedResponse = fetchResponse; |
| 158 | + for (const interceptor of this.responseInterceptors) { |
| 159 | + processedResponse = (await interceptor(processedResponse)) as FetchResponse<T>; |
| 160 | + } |
| 161 | + |
| 162 | + return processedResponse; |
| 163 | + } catch (error) { |
| 164 | + // Apply error interceptors |
| 165 | + let processedError = createFormattedError(error as Error, 0, 'Network error. Please check your connection and try again.'); |
| 166 | + for (const interceptor of this.errorInterceptors) { |
| 167 | + const result = await interceptor(processedError); |
| 168 | + if (result !== undefined) { |
| 169 | + processedError = result; |
| 170 | + } |
| 171 | + } |
| 172 | + |
| 173 | + throw processedError; |
| 174 | + } |
| 175 | + } |
| 176 | +} |
| 177 | + |
| 178 | +/** |
| 179 | + * Create fetch client instance |
| 180 | + */ |
| 181 | +const fetchInstance = new FetchInstance(); |
| 182 | + |
| 183 | +/** |
| 184 | + * Callable fetch client that defaults to GET requests |
| 185 | + */ |
| 186 | +export const FetchClient = Object.assign(async <T = unknown>(url: string, config?: Omit<RequestConfig, 'method' | 'url'>): Promise<T> => { |
| 187 | + const response = await fetchInstance.request<T>({ ...config, method: 'GET', url }); |
| 188 | + return response.data; |
| 189 | +}, fetchInstance); |
| 190 | + |
| 191 | +// Export the client instance for direct use |
| 192 | +export default FetchClient; |
0 commit comments