All files / src APIClient.ts

83.33% Statements 25/30
64.7% Branches 11/17
100% Functions 5/5
83.33% Lines 25/30

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 872x               2x         1x       1x                 5x   5x 8x 8x 8x   8x                     4x 1x                 1x         1x 1x   1x 2x 2x     2x 2x       2x     1x       3x 1x   2x        
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
 
interface APIClientConfig {
    baseURL: string;
    timeout?: number;
    retries?: number;
}
 
export class APIClient {
    private axiosInstance: AxiosInstance;
    private retries: number;
 
    constructor(config: APIClientConfig) {
        this.axiosInstance = axios.create({
            baseURL: config.baseURL,
            timeout: config.timeout || 5000,
        });
        this.retries = config.retries || 3;
    }
 
    public async requestWithRetry<T>(
        method: 'GET' | 'POST' | 'PUT' | 'DELETE',
        url: string,
        data?: unknown,
        config?: AxiosRequestConfig
    ): Promise<AxiosResponse<T>> {
        let attempts = 0;
 
        while (attempts < this.retries) {
            try {
                attempts++;
                switch (method) {
                    case 'GET':
                        return await this.axiosInstance.get<T>(url, config);
                    case 'POST':
                        return await this.axiosInstance.post<T>(url, data, config);
                    case 'PUT':
                        return await this.axiosInstance.put<T>(url, data, config);
                    case 'DELETE':
                        return await this.axiosInstance.delete<T>(url, config);
                    default:
                        throw new Error(`Unsupported HTTP method: ${method}`);
                }
            } catch (error) {
                if (attempts >= this.retries) {
                    this.handleError(error as AxiosError); // Throw the error after max retries
                }
            }
        }
 
        throw new Error('Request failed after max retries.'); // Fallback, though retries handle this
    }
 
    async fetchPaginated<T>(
        url: string,
        config?: AxiosRequestConfig,
        paginationKey: string = 'next',
        resultsKey: string = 'data'
    ): Promise<T[]> {
        const results: T[] = [];
        let nextPage: string | null = url;
 
        while (nextPage) {
            const response = await this.requestWithRetry<T>(`GET`, nextPage, undefined, config);
            const responseData = response.data as Record<string, unknown>;
 
            // Collect results
            if (Array.isArray(responseData[resultsKey])) {
                results.push(...(responseData[resultsKey] as T[]));
            }
 
            // Determine the next page
            nextPage = (responseData[paginationKey] as string) || null;
        }
 
        return results;
    }
 
    private handleError(error: AxiosError): never {
        if (error.response) {
            throw error;
        } else {
            throw new Error(`Error: ${error.message}`);
        }
    }
}