@pavansapkale/x-fetch
v1.0.1
Published
A lightweight, type-safe wrapper around the native Fetch API for frontend projects.
Readme
x-fetch
A lightweight, type-safe wrapper around the native Fetch API for frontend projects.
Features
- 🚀 Lightweight: Minimal overhead over native
fetch. - 🔒 Type-Safe: Built with TypeScript for excellent developer experience.
- 🛠 Configurable: Support for
baseURL, default headers, and more. - 🔌 Interceptors: (Coming Soon) Hooks for request and response manipulation.
- 📦 ESM & CJS: Dual build support for modern and legacy environments.
Installation
npm install x-fetch
# or
yarn add x-fetch
# or
pnpm add x-fetchUsage
Basic Usage
Use the global xFetch instance for quick requests.
import { xFetch } from 'x-fetch';
// GET Request
const [data, error] = await xFetch.get('/api/users');
if (error) return console.error(error);
console.log(data);
// POST Request
const newUser = { name: 'John Doe', email: '[email protected]' };
const [response, err] = await xFetch.post('/api/users', newUser);Custom Instance
Create a custom instance to set a baseURL or default options.
import { XFetch } from 'x-fetch';
const api = new XFetch({
baseURL: 'https://api.example.com/v1',
headers: {
'Authorization': 'Bearer token',
},
});
// Requests will be relative to baseURL
const [users, error] = await api.get('/users');TypeScript Support
You can define the expected response type for better type safety.
interface User {
id: number;
name: string;
}
const [user, error] = await xFetch.get<User>('/users/1');
if (user) {
console.log(user.name);
}Advanced Usage
Timeout
Set a timeout in milliseconds. The request will be aborted if it takes longer than the specified time.
try {
const data = await xFetch.get('/long-running-task', { timeout: 5000 });
} catch (error) {
if (error.name === 'AbortError') {
console.log('Request timed out');
}
}Retry Mechanism
Configure automatic retries for failed requests.
const data = await xFetch.get('/unstable-api', {
retry: {
retries: 3, // Number of retries
retryDelay: 1000, // Delay between retries in ms
retryOn: [500, 503] // HTTP status codes to retry on (default: 5xx if not specified)
}
});Interceptors
Intercept requests and responses to inject headers, log data, or handle errors globally.
const api = new XFetch({
baseURL: 'https://api.example.com',
interceptors: {
request: async (config) => {
// Add auth token
const token = localStorage.getItem('token');
if (token) {
config.headers = { ...config.headers, Authorization: `Bearer ${token}` };
}
console.log('Requesting:', config.url);
return config;
},
response: async (response) => {
console.log('Response status:', response.status);
return response;
},
error: (error) => {
console.error('Global error handler:', error);
throw error;
}
}
});Query Parameters
Automatically serialize query parameters.
// GET /users?page=1&sort=asc&tags=a&tags=b
await xFetch.get('/users', {
params: {
page: 1,
sort: 'asc',
tags: ['a', 'b']
}
});Response Types
Specify the expected response type.
// Get an image as a Blob
const imageBlob = await xFetch.get('/avatar.png', { responseType: 'blob' });Error Handling
x-fetch returns a tuple [data, error]. You don't need try-catch blocks!
const [data, error] = await xFetch.get('/api/protected');
if (error) {
console.error(`Error ${error.status}: ${error.statusText}`);
console.error('Response Body:', error.data);
return;
}
// data is safe to use here
console.log(data);Caching
Cache responses in memory or local storage with TTL support.
// Cache for 5 minutes in memory
await xFetch.get('/api/config', {
cache: {
ttl: 5 * 60 * 1000,
storage: 'memory' // or 'localStorage', 'sessionStorage'
}
});
// Force update (ignore cache)
await xFetch.get('/api/config', {
cache: {
ttl: 5 * 60 * 1000,
forceUpdate: true
}
});API
new XFetch(options)
Creates a new instance of XFetch.
options.baseURL(string): Base URL for all requests.options.timeout(number): Default timeout in milliseconds.options.retry(RetryConfig): Default retry configuration.options.cache(CacheConfig): Default cache configuration.options.responseType(ResponseType): Default response type ('json', 'text', 'blob', etc.).options.headers(HeadersInit): Default headers to include in every request.options.interceptors(object):request: Function to modify config before request.response: Function to handle response before returning.error: Function to handle errors globally.
Methods
get<T>(url, options): Performs a GET request.post<T>(url, data, options): Performs a POST request.put<T>(url, data, options): Performs a PUT request.patch<T>(url, data, options): Performs a PATCH request.delete<T>(url, options): Performs a DELETE request.head<T>(url, options): Performs a HEAD request.options<T>(url, options): Performs an OPTIONS request.request<T>(url, options): Generic request method.
License
ISC
