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
npm install @uiblock/http-clientA 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.
⨠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 AbortController to 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
Install from npm (scoped package):
``bash`
npm install @uiblock/http-client
Or with yarn:
`bash`
yarn add @uiblock/http-client
`typescript
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: "john@example.com",
});
`
For detailed usage examples, see HOW_TO_USE.md
`bash`
npm test
MIT
// Batch requests
const responses = await client.batch([
{ method: 'GET', url: '/endpoint1' },
{ method: 'POST', url: '/endpoint2', data: { key: 'value' } }
]);
``
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;
});
``
You can set up automatic transformations for request and response data:
`c
client.setTransformRequest(data => {
return { ...data, transformed: true };
});
client.setTransformResponse(data => {
return data.result;
});
`
Track the progress of upload and download requests:
`cUploaded: ${loaded} of ${total}
await client.post('/upload', formData, {
onUploadProgress: (loaded, total) => {
console.log();Downloaded: ${loaded} of ${total}
},
onDownloadProgress: (loaded, total) => {
console.log();`
},
});
Cancel requests using cancellation tokens:
`c
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();
`
Configure retry logic with exponential backoff:
`c`
await client.requestWithRetry('GET', '/endpoint', {}, {}, 3); // Retry 3 times on failure
Implement rate limiting to avoid hitting API limits:
`c`
client.setRateLimit(1000); // Limit requests to 1 per second
Send multiple requests in a single HTTP call:
`c`
const responses = await client.batch([
{ method: 'GET', url: '/endpoint1' },
{ method: 'POST', url: '/endpoint2', data: { key: 'value' } },
]);
MethodThe 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.
`c``
fetchAndModifyData
initialUrl: string,
modifyFn: (data: T) => U,
finalUrl: string,
options?: RequestOptions
): Promise
⢠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.