luhanxin-http-utils
v1.0.5
Published
Enterprise-level HTTP SDK with multi-client, chain of responsibility, cross-end adapter
Downloads
698
Maintainers
Readme
HTTP Utils
A cross-platform HTTP client library for Web, MiniProgram (WeChat), React Native, Electron, and Node.js environments.
Features
- Unified API: Same API across different JavaScript environments
- Adapter-based: Plugable adapters for different platforms
- Middleware chains: Request, response, and error middleware chains
- Interceptor support: Easy-to-use interceptor methods
- Cache & Debounce: Built-in request caching and debouncing
- Retry & Timeout: Automatic retry with configurable delay
- TypeScript: Fully typed with TypeScript
Installation
npm install luhanxin-http-utils
# or
pnpm add luhanxin-http-utilsQuick Start
import { RequestClient, ClientManager } from 'http-utils';
// Create a client
const client = new RequestClient('my-client', 'https://api.example.com');
// Add interceptors
client.useRequestInterceptor(async (ctx, next) => {
console.log(`Sending ${ctx.config.method} request to ${ctx.fullUrl}`);
ctx.config.headers['Authorization'] = 'Bearer token';
await next();
});
client.useResponseInterceptor(async (ctx, next) => {
await next();
console.log(`Received response: ${ctx.response?.status}`);
});
// Make requests
const posts = await client.get('/posts');
const newPost = await client.post('/posts', { title: 'Hello' });
// Register client for global access
ClientManager.register(client);
const defaultClient = ClientManager.getDefault();Configuration
const config = {
domain: 'https://api.example.com',
timeout: 10000, // Request timeout in ms
retry: 3, // Number of retries
retryDelay: 1000, // Delay between retries in ms
cache: true, // Enable caching (GET requests only)
debounce: 300, // Debounce time in ms
responseType: 'json', // 'json' | 'text' | 'blob' | 'arrayBuffer' | 'formData'
headers: { // Default headers
'Content-Type': 'application/json',
},
};Supported Environments
- Web: Uses Fetch API
- WeChat MiniProgram: Uses
wx.request - React Native: Uses Fetch API
- Electron: Uses Fetch API
- Node.js: Uses http/https modules (NodeAdapter)
The library automatically detects the environment and selects the appropriate adapter.
Advanced Usage
Multiple Clients
const apiClient = new RequestClient('api', 'https://api.example.com');
const authClient = new RequestClient('auth', 'https://auth.example.com');
ClientManager.register(apiClient);
ClientManager.register(authClient);
const client = ClientManager.get('api');Sub-clients
const mainClient = new RequestClient('main', 'https://api.example.com');
const postsClient = mainClient.createSubClient('posts');
// postsClient inherits middleware and configuration from mainClientCustom Adapters
Implement the Adapter interface and use AdapterFactory.setEnvironment() to override.
Error Handling
try {
await client.get('/protected');
} catch (error) {
if (error.status === 401) {
// Handle unauthorized
}
}API Reference
RequestClient
new RequestClient(name, domain, defaultConfig)request(config): Promise<Response>get(url, params, config)post(url, data, config)put(url, data, config)delete(url, config)withConfig(config): thiswithDomain(domain): thisuseRequestInterceptor(fn): thisuseResponseInterceptor(fn): thisuseErrorInterceptor(fn): thiscreateSubClient(name, config): RequestClient
ClientManager
register(client): voidget(name): RequestClient | undefinedgetDefault(): RequestClient
AdapterFactory
getAdapter(): AdaptersetEnvironment(env): voidgetEnvironment(): EnvType
Building
pnpm install
pnpm buildLicense
MIT
