// fetchUtils.ts
/**
* HTTP request methods
*/
export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
/**
* Custom error class for API requests
*/
export class ApiError extends Error {
public status: number;
public statusText: string;
public data: any;
public isApiError = true;
constructor(status: number, statusText: string, data?: any) {
super(`API Error: ${status} ${statusText}`);
this.name = 'ApiError';
this.status = status;
this.statusText = statusText;
this.data = data;
}
}
/**
* Interface for request options
*/
export interface RequestOptions<T = any> extends Omit<RequestInit, 'body'> {
baseUrl?: string;
params?: Record<string, string | number | boolean | undefined | null>;
data?: T;
timeout?: number;
retries?: number;
retryDelay?: number;
withCredentials?: boolean;
}
/**
* Interface for response with typed data
*/
export interface ApiResponse<T> {
data: T;
status: number;
statusText: string;
headers: Headers;
raw: Response;
}
/**
* Formats URL with query parameters
*/
function formatUrl(url: string, baseUrl?: string, params?: Record<string, any>): string {
const fullUrl = baseUrl ? `${baseUrl.replace(/\/$/, '')}/${url.replace(/^\//, '')}` : url;
if (!params) return fullUrl;
const queryParams = new URLSearchParams();
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
queryParams.append(key, String(value));
}
});
const queryString = queryParams.toString();
return queryString ? `${fullUrl}${fullUrl.includes('?') ? '&' : '?'}${queryString}` : fullUrl;
}
/**
* Creates a timeout promise that rejects after specified milliseconds
*/
function timeoutPromise(ms: number): Promise<never> {
return new Promise((_, reject) => {
setTimeout(() => reject(new ApiError(408, 'Request Timeout')), ms);
});
}
/**
* Parses response based on content type
*/
async function parseResponse(response: Response): Promise<any> {
const contentType = response.headers.get('content-type') || '';
if (contentType.includes('application/json')) {
return response.json().catch(() => ({}));
} else if (contentType.includes('text/')) {
return response.text();
} else if (contentType.includes('form')) {
return response.formData();
} else if (contentType.includes('multipart/form-data')) {
return response.formData();
} else if (contentType.includes('application/octet-stream')) {
return response.blob();
}
return response.text();
}
/**
* Main fetch function with error handling, retries, and timeouts
*/
export async function fetchApi<T = any>(
url: string,
method: HttpMethod = 'GET',
options: RequestOptions = {}
): Promise<ApiResponse<T>> {
const {
baseUrl,
params,
data,
timeout = 30000,
retries = 0,
retryDelay = 1000,
withCredentials = false,
headers = {},
...restOptions
} = options;
const formattedUrl = formatUrl(url, baseUrl, params);
// Prepare headers
const requestHeaders = new Headers(headers);
if (!requestHeaders.has('Content-Type') && data && !(data instanceof FormData)) {
requestHeaders.set('Content-Type', 'application/json');
}
// Prepare body
let body: any = undefined;
if (data !== undefined) {
if (data instanceof FormData) {
body = data;
} else if (typeof data === 'object' && data !== null) {
body = JSON.stringify(data);
} else {
body = String(data);
}
}
// Prepare fetch options
const fetchOptions: RequestInit = {
method,
headers: requestHeaders,
body: ['GET', 'HEAD'].includes(method) ? undefined : body,
credentials: withCredentials ? 'include' : 'same-origin',
...restOptions,
};
// Execute fetch with timeout and retries
let lastError: Error | null = null;
let attempt = 0;
while (attempt <= retries) {
try {
// Create a race between fetch and timeout
const response = await Promise.race([
fetch(formattedUrl, fetchOptions),
timeoutPromise(timeout)
]);
// Parse response data
const responseData = await parseResponse(response);
// Handle error responses
if (!response.ok) {
throw new ApiError(response.status, response.statusText, responseData);
}
// Return successful response
return {
data: responseData as T,
status: response.status,
statusText: response.statusText,
headers: response.headers,
raw: response
};
} catch (error) {
lastError = error as Error;
// Don't retry if it's not a network error or timeout
if (error instanceof ApiError && error.status !== 408 && error.status < 500) {
throw error;
}
// If we have retries left, wait and try again
if (attempt < retries) {
await new Promise(resolve => setTimeout(resolve, retryDelay));
attempt++;
} else {
throw lastError;
}
}
}
// This should never be reached due to the throw in the loop
throw lastError || new Error('Unknown error occurred');
}
/**
* Convenience methods for different HTTP verbs
*/
export const api = {
get<T = any>(url: string, options?: RequestOptions): Promise<ApiResponse<T>> {
return fetchApi<T>(url, 'GET', options);
},
post<T = any>(url: string, data?: any, options?: RequestOptions): Promise<ApiResponse<T>> {
return fetchApi<T>(url, 'POST', { ...options, data });
},
put<T = any>(url: string, data?: any, options?: RequestOptions): Promise<ApiResponse<T>> {
return fetchApi<T>(url, 'PUT', { ...options, data });
},
patch<T = any>(url: string, data?: any, options?: RequestOptions): Promise<ApiResponse<T>> {
return fetchApi<T>(url, 'PATCH', { ...options, data });
},
delete<T = any>(url: string, options?: RequestOptions): Promise<ApiResponse<T>> {
return fetchApi<T>(url, 'DELETE', options);
}
};
/**
* Check if an error is an ApiError
*/
export function isApiError(error: any): error is ApiError {
return error && error.isApiError === true;
}