@uiblock/http-client
v1.0.0
Published
A powerful, fully customizable, and extensible HTTP client built with TypeScript. This library provides enterprise-grade features like automatic transformations, request/response interceptors, progress tracking, request cancellation, retry logic with expo
Readme
Feature-Rich TypeScript HTTP Client
A powerful, fully customizable, and extensible HTTP client built with TypeScript. This library provides enterprise-grade features like automatic transformations, request/response interceptors, progress tracking, request cancellation, retry logic with exponential backoff, rate limiting, and batch requests. Perfect for Node.js and browser environments.
Features
✨ Core Features
- 🔄 Request & Response Interceptors - Add custom logic before requests are sent and after responses are received
- 🎯 Automatic Data Transformation - Transform request/response data automatically
- 📊 Progress Tracking - Monitor upload and download progress in real-time
- ❌ Request Cancellation - Use
AbortControllerto cancel ongoing requests - 🔁 Retry Logic with Exponential Backoff - Automatically retry failed requests with smart backoff
- ⏱️ Rate Limiting - Control request frequency to avoid overwhelming APIs
- 📦 Batch Requests - Execute multiple requests in parallel efficiently
- ⏰ Timeouts - Set time limits on requests
- 🛡️ Error Handling - Comprehensive error handling with customizable behavior
Installation
Install from npm (scoped package):
npm install @uiblock/http-clientOr with yarn:
yarn add @uiblock/http-clientQuick Start
import { HttpClient } from "@uiblock/http-client";
// Initialize the client
const client = new HttpClient("https://api.example.com", {
"Content-Type": "application/json",
Authorization: "Bearer YOUR_TOKEN",
});
// Make a simple GET request
const data = await client.get("/users/1");
console.log(data);
// Make a POST request
const newUser = await client.post("/users", {
name: "John Doe",
email: "[email protected]",
});Documentation
For detailed usage examples, see HOW_TO_USE.md
Testing
npm testLicense
MIT
// Batch requests const responses = await client.batch([ { method: 'GET', url: '/endpoint1' }, { method: 'POST', url: '/endpoint2', data: { key: 'value' } } ]);
## Request & Response Interceptors
You can add interceptors for both requests and responses:
```c
// Request interceptor
client.interceptors.request.use(config => {
console.log('Request sent with config:', config);
return config;
});
// Response interceptor
client.interceptors.response.use(response => {
console.log('Response received:', response);
return response;
});
Automatic Transformations
You can set up automatic transformations for request and response data:
client.setTransformRequest(data => {
return { ...data, transformed: true };
});
client.setTransformResponse(data => {
return data.result;
});Progress Tracking
Track the progress of upload and download requests:
await client.post('/upload', formData, {
onUploadProgress: (loaded, total) => {
console.log(`Uploaded: ${loaded} of ${total}`);
},
onDownloadProgress: (loaded, total) => {
console.log(`Downloaded: ${loaded} of ${total}`);
},
});Cancellation
Cancel requests using cancellation tokens:
const controller = new AbortController();
const signal = controller.signal;
client.get('/endpoint', { signal }).catch(err => {
if (err.name === 'AbortError') {
console.log('Request was cancelled');
}
});
// Cancel the request
controller.abort();Retry Logic
Configure retry logic with exponential backoff:
await client.requestWithRetry('GET', '/endpoint', {}, {}, 3); // Retry 3 times on failureRate Limiting
Implement rate limiting to avoid hitting API limits:
client.setRateLimit(1000); // Limit requests to 1 per secondBatch Requests
Send multiple requests in a single HTTP call:
const responses = await client.batch([
{ method: 'GET', url: '/endpoint1' },
{ method: 'POST', url: '/endpoint2', data: { key: 'value' } },
]);fetchAndModifyData Method
The fetchAndModifyData method allows you to make an initial API call, modify the received data using a provided function, and then make a subsequent API call using the modified data. This is useful for scenarios where you need to fetch some data, transform it, and then submit or use that data in another request.
Signature
fetchAndModifyData<T, U>(
initialUrl: string,
modifyFn: (data: T) => U,
finalUrl: string,
options?: RequestOptions
): Promise<any>Parameters
• initialUrl (string): The URL for the initial API call.
• modifyFn ((data: T) => U): A function that takes the response from the initial API call and modifies it. The function should return the modified data.
• finalUrl (string): The URL for the subsequent API call using the modified data.
• options (RequestOptions, optional): An optional object that can include headers, timeout settings, and other request-specific options.