abit-fetch
v1.0.2
Published
abit-fetch http requests from scratch
Maintainers
Readme
AbitFetch - Lightweight Fetch API Wrapper
AbitFetch is a lightweight wrapper around the Fetch API with interceptors support, request/response transformations, and singleton pattern implementation.
Features
- Singleton pattern implementation
- Request and response interceptors
- Automatic Content-Type header handling
- Support for various response types (JSON, text, blob, arraybuffer)
- Query parameter handling
- Timeout support (default: 5 seconds)
- All standard HTTP methods (GET, POST, PUT, DELETE, etc.)
- TypeScript support
Installation
npm install abit-fetch
# or
yarn add abit-fetchUsage
Basic Example
import AbitFetch from 'abit-fetch';
const api = AbitFetch.getInstance({
baseURL: 'https://api.example.com',
headers: {
Authorization: 'Bearer token',
},
});
// GET request
const response = await api.get('/users');
// POST request
const createResponse = await api.post('/users', {
data: { name: 'John Doe' },
});Interceptors
// Add request interceptor
api.interceptors.request.use((config) => {
// Modify config or add headers
config.headers.set('X-Custom-Header', 'value');
return config;
});
// Add response interceptor
api.interceptors.response.use(
(response) => {
// Process response data
console.log('Response received');
return response;
},
(error) => {
// Handle error
console.error('Request failed:', error);
return Promise.reject(error);
},
);Configuration Options
{
baseURL?: string; // Base URL for all requests
url?: string; // Request URL
method?: string; // HTTP method (GET, POST, etc.)
headers?: HeadersInit; // Request headers
params?: Record<string, any>; // URL parameters
data?: any; // Request body
responseType?: 'json' | 'text' | 'blob' | 'arraybuffer'; // Response type
signal?: AbortSignal; // Abort signal
}
`Available Methods
get(url, config);
post(url, config);
put(url, config);
patch(url, config);
delete (url, config);
head(url, config);
options(url, config);Error Handling
AbitFetch throws errors with additional information in the cause property:
try {
await api.get('/nonexistent');
} catch (error) {
console.error('Status code:', error.cause.status);
console.error('Message:', error.message);
}License MIT
