universal-api-handler
v1.0.2
Published
A lightweight TypeScript-based HTTP API handler with retry logic, request/response interceptors, and file download support
Maintainers
Readme
universal-api-handler
A lightweight TypeScript-based HTTP API handler with built-in retry logic, request/response interceptors, and file download support.
Features
- 🔄 Automatic Retry: Retry failed requests with configurable delays
- 🔗 Request/Response Interceptors: Intercept and modify requests and responses
- 📥 File Downloads: Download files with progress tracking
- 🔒 TypeScript Support: Fully typed for better IDE support
- 🪶 Lightweight: Minimal dependencies, uses native Fetch API
- 🛡️ Error Handling: Built-in error handling and status code detection
Installation
npm install universal-api-handlerUsage
Basic Setup
import ApiHandler from 'universal-api-handler';
const api = ApiHandler({
baseUrl: 'https://api.example.com',
headers: {
'Authorization': 'Bearer token'
}
});GET Request
const response = await api.get('/users', {
params: {
page: '1',
limit: '10'
}
});
console.log(response.data);POST Request
const response = await api.post('/users', {
payload: {
name: 'John Doe',
email: '[email protected]'
}
});PUT Request
const response = await api.put('/users/1', {
payload: {
name: 'Jane Doe'
}
});Retry Configuration
const api = ApiHandler({
baseUrl: 'https://api.example.com',
errorRetry: {
retryTimes: 3,
retryDelay: 1000,
onRetry: (info) => {
console.log(`Retrying ${info.method} ${info.api}`);
}
}
});Request/Response Interceptors
const api = ApiHandler({
baseUrl: 'https://api.example.com'
});
// Modify requests before sending
api.config.request((options) => {
options.headers = {
...options.headers,
'X-Custom-Header': 'value'
};
return options;
});
// Modify responses
api.config.response((response) => {
console.log('Response received:', response);
return response;
});File Downloads
await api.download('/files/document.pdf', {
fileName: 'document.pdf',
onDownloadProgress: (percentage) => {
console.log(`Downloaded: ${percentage}%`);
}
});API Reference
ApiHandler(options)
Creates and returns an API handler instance.
Options:
baseUrl(string): The base URL for all requestsheaders(HeadersInit, optional): Default headers to include in all requestsconfig(RequestInit, optional): Default fetch configurationerrorRetry(ErrorRetryConfig, optional): Retry configuration
Methods
get(endpoint, options): Send a GET requestpost(endpoint, options): Send a POST requestput(endpoint, options): Send a PUT requestdownload(endpoint, options): Download a file
Options:
params(Record<string, string>): Query parameterspayload(any): Request body (for POST/PUT)headers(HeadersInit): Additional headers for this requestretryTimes(number): Override retry times for this requestretryDelay(number): Override retry delay for this requestonRetry(function): Callback when a retry occursfileName(string): File name for downloadsonDownloadProgress(function): Callback for download progress
License
MIT
