UNPKG

fetch-api-client

Version:

A TypeScript API client using fetch with axios-like interface

119 lines (118 loc) 3.79 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ResponseInterceptorManager = exports.RequestInterceptorManager = void 0; /** * Generic interceptor manager implementation */ class InterceptorManagerImpl { constructor() { this.interceptors = new Map(); this.nextId = 0; } /** * Add an interceptor and return its ID */ use(interceptor) { const id = this.nextId++; this.interceptors.set(id, interceptor); return id; } /** * Remove an interceptor by ID */ eject(id) { this.interceptors.delete(id); } /** * Clear all interceptors */ clear() { this.interceptors.clear(); } /** * Get all interceptors as an array */ getInterceptors() { return Array.from(this.interceptors.values()); } } /** * Request interceptor manager */ class RequestInterceptorManager extends InterceptorManagerImpl { /** * Execute all request interceptors in sequence */ async execute(config) { let processedConfig = config; for (const interceptor of this.getInterceptors()) { try { processedConfig = await interceptor(processedConfig); } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown interceptor error'; console.warn('Request interceptor failed:', errorMessage); } } return processedConfig; } } exports.RequestInterceptorManager = RequestInterceptorManager; /** * Response interceptor manager */ class ResponseInterceptorManager extends InterceptorManagerImpl { /** * Execute fulfilled interceptors */ async executeFulfilled(response) { let processedResponse = response; for (const interceptor of this.getInterceptors()) { if (interceptor.onFulfilled) { try { processedResponse = await interceptor.onFulfilled(processedResponse); } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown interceptor error'; console.warn('Response interceptor (fulfilled) failed:', errorMessage); } } } return processedResponse; } /** * Execute rejected interceptors - Fixed to handle proper return types */ async executeRejected(error) { let processedError = error; for (const interceptor of this.getInterceptors()) { if (interceptor.onRejected) { try { const result = await interceptor.onRejected(processedError); // Ensure we only work with ApiError types if (this.isApiError(result)) { processedError = result; } else { console.warn('Response interceptor returned invalid type, using original error'); } } catch (interceptorError) { const errorMessage = interceptorError instanceof Error ? interceptorError.message : 'Unknown interceptor error'; console.warn('Response interceptor (rejected) failed:', errorMessage); } } } return processedError; } /** * Type guard to check if result is ApiError */ isApiError(obj) { return obj && typeof obj === 'object' && typeof obj.message === 'string' && typeof obj.code === 'string'; } } exports.ResponseInterceptorManager = ResponseInterceptorManager;