@chittyos/http-client
v1.0.1
Published
Type-safe HTTP client with retry logic for ChittyOS Framework
Downloads
18
Maintainers
Readme
@chittyos/http-client
Type-safe HTTP client with retry logic for ChittyOS Framework.
Installation
npm install @chittyos/http-clientUsage
Basic Usage
import { HttpClient } from '@chittyos/http-client';
// Create client with base URL
const client = new HttpClient({
baseURL: 'https://api.example.com',
timeout: 30000,
headers: {
'Authorization': 'Bearer token',
},
});
// Make requests
const users = await client.get('/users');
const newUser = await client.post('/users', { name: 'John' });
const updated = await client.put('/users/123', { name: 'Jane' });
await client.delete('/users/123');ChittyOS HTTP Client
import { createChittyOSHttpClient } from '@chittyos/http-client';
// Create client with ChittyOS defaults
const client = createChittyOSHttpClient({
baseURL: 'https://api.chitty.cc',
});
// Includes automatic retry logic and ChittyOS headers
const response = await client.get('/health');Service-Specific Client
import { createServiceHttpClient } from '@chittyos/http-client';
// Create client for specific ChittyOS service
const chittyidClient = createServiceHttpClient(
'chittyid',
'https://id.chitty.cc'
);
// Automatically includes service identifier in headers
const id = await chittyidClient.post('/v1/mint', {
entity: 'PEO',
trust: 'verified',
});HTTP Methods
import { HttpClient } from '@chittyos/http-client';
const client = new HttpClient({ baseURL: 'https://api.example.com' });
// GET request
const users = await client.get<User[]>('/users');
// POST request with body
const newUser = await client.post<User>('/users', {
name: 'John',
email: '[email protected]',
});
// PUT request
const updated = await client.put<User>('/users/123', {
name: 'Jane',
});
// PATCH request
const patched = await client.patch<User>('/users/123', {
active: false,
});
// DELETE request
await client.delete('/users/123');
// HEAD request
await client.head('/users/123');Retry Configuration
import { createChittyOSHttpClient } from '@chittyos/http-client';
const client = createChittyOSHttpClient({
baseURL: 'https://api.example.com',
retry: {
maxRetries: 5, // Maximum retry attempts
initialDelay: 1000, // Initial delay (1 second)
maxDelay: 30000, // Maximum delay (30 seconds)
backoffFactor: 2, // Exponential backoff multiplier
retryableStatuses: [ // Status codes that trigger retry
408, // Request Timeout
429, // Too Many Requests
500, // Internal Server Error
502, // Bad Gateway
503, // Service Unavailable
504, // Gateway Timeout
],
retryOnNetworkError: true, // Retry on network failures
},
});
// Automatically retries on failure with exponential backoff
const response = await client.get('/users');Request Interceptors
import { HttpClient } from '@chittyos/http-client';
const client = new HttpClient({
baseURL: 'https://api.example.com',
});
// Add authentication interceptor
client.addRequestInterceptor((config) => {
return {
...config,
headers: {
...config.headers,
'Authorization': `Bearer ${getToken()}`,
},
};
});
// Add logging interceptor
client.addRequestInterceptor(async (config) => {
console.log(`[HTTP] ${config.method} ${config.url}`);
return config;
});
// All requests will include the intercepted headers
await client.get('/users');Response Interceptors
import { HttpClient } from '@chittyos/http-client';
const client = new HttpClient({
baseURL: 'https://api.example.com',
});
// Add response logging interceptor
client.addResponseInterceptor((response) => {
console.log(`[HTTP] ${response.status} ${response.url}`);
return response;
});
// Add response transformation interceptor
client.addResponseInterceptor(async (response) => {
// Could modify response before returning
return response;
});
await client.get('/users');Error Interceptors
import { HttpClient } from '@chittyos/http-client';
import { NetworkError } from '@chittyos/types';
const client = new HttpClient({
baseURL: 'https://api.example.com',
});
// Add error logging interceptor
client.addErrorInterceptor((error) => {
console.error('[HTTP Error]', error.message);
return error;
});
// Add custom error transformation
client.addErrorInterceptor((error) => {
if (error instanceof NetworkError && error.statusCode === 401) {
// Handle authentication errors
redirectToLogin();
}
return error;
});
try {
await client.get('/protected');
} catch (error) {
// Error has been processed by interceptors
}Timeout Control
import { HttpClient } from '@chittyos/http-client';
import { TimeoutError } from '@chittyos/types';
const client = new HttpClient({
baseURL: 'https://api.example.com',
timeout: 5000, // 5 second default timeout
});
try {
// Override timeout for specific request
const response = await client.get('/slow-endpoint', {
timeout: 30000, // 30 second timeout
});
} catch (error) {
if (error instanceof TimeoutError) {
console.error('Request timed out after', error.timeout, 'ms');
}
}Custom Headers
import { HttpClient } from '@chittyos/http-client';
const client = new HttpClient({
baseURL: 'https://api.example.com',
headers: {
'X-API-Key': 'your-api-key',
'X-Client-Version': '1.0.0',
},
});
// Override headers for specific request
await client.get('/users', {
headers: {
'X-Request-ID': 'unique-request-id',
},
});Error Handling
import { HttpClient } from '@chittyos/http-client';
import { NetworkError, TimeoutError } from '@chittyos/types';
const client = new HttpClient({
baseURL: 'https://api.example.com',
});
try {
const response = await client.get('/users');
} catch (error) {
if (error instanceof TimeoutError) {
console.error('Request timed out:', error.timeout);
} else if (error instanceof NetworkError) {
console.error('Network error:', error.statusCode, error.url);
} else {
console.error('Unknown error:', error);
}
}API Reference
HttpClient
Main HTTP client class with retry logic and interceptors.
Constructor Options:
baseURL?: string- Base URL for all requeststimeout?: number- Default timeout in milliseconds (default: 30000)headers?: Record<string, string>- Default headersretry?: RetryConfig- Retry configurationrequestInterceptors?: RequestInterceptor[]- Request interceptorsresponseInterceptors?: ResponseInterceptor[]- Response interceptorserrorInterceptors?: ErrorInterceptor[]- Error interceptors
Methods:
get<T>(url, config?)- GET requestpost<T>(url, body?, config?)- POST requestput<T>(url, body?, config?)- PUT requestpatch<T>(url, body?, config?)- PATCH requestdelete<T>(url, config?)- DELETE requesthead(url, config?)- HEAD requestrequest<T>(config)- Generic requestaddRequestInterceptor(interceptor)- Add request interceptoraddResponseInterceptor(interceptor)- Add response interceptoraddErrorInterceptor(interceptor)- Add error interceptor
createChittyOSHttpClient(config?)
Create HTTP client with ChittyOS defaults (User-Agent, retry logic, etc.).
createServiceHttpClient(service, baseURL, config?)
Create HTTP client for specific ChittyOS service with service identifier header.
Features
- ✅ Type-safe HTTP requests with TypeScript
- ✅ Automatic retry with exponential backoff
- ✅ Timeout control with AbortController
- ✅ Request/response/error interceptors
- ✅ Configurable retry logic
- ✅ Network error handling
- ✅ JSON body serialization
- ✅ ChittyOS integration (service headers, defaults)
- ✅ Zero runtime dependencies (except @chittyos/types and @chittyos/config)
Package Size
~35KB (gzipped)
License
MIT
