sim-fetchx v1.0.4
API Documentation
SimFetchX
is a lightweight đ, configurable âī¸, and retry-enabled đ HTTP client for making API requests. It supports caching đž, retries đ, timeouts âŗ, and streaming đ, making it ideal for handling unreliable network conditions đļ and large data transfers.
Table of Contents
Installation âŗī¸
To use SimFetchX
, install it via npm:
npm install sim-fetchx
Usage
Run test within the the lib folder
npm test
Initialization âŗī¸
To start using SimFetchX
, create an instance by passing a configuration object.
import { SimFetchX } from 'sim-fetchx';
const api = new SimFetchX({
baseUrl: 'https://api.example.com',
timeout: 5000, // Optional: Default timeout is 5 seconds
retry: true, // Optional: Enable retries (default is true)
retryNumber: 3, // Optional: Number of retries (default is 5)
cacheTtl: 60000, // Optional: Cache TTL in milliseconds (default is 1 minute)
});
Making Requests âŗī¸
Use the available methods (get
, post
, put
, delete
, etc.) to make HTTP requests.
Caching
Responses are cached for 1 minute (default) to reduce redundant requests. You can clear the cache using clearCache()
.
Retries
If a request fails due to a server error (5xx) or timeout, SimFetchX
will automatically retry the request up to the specified number of times.
Streaming âŗī¸
SimFetchX
supports streaming large responses using the stream()
method. This is useful for downloading files or processing data in chunks.
Error Handling
SimFetchX
provides detailed error handling, including status codes, error messages, and retry logic.
API Methods đšī¸
get
Makes a GET request.
async get(path: string, options?: IOption): Promise<Response>
Example:
const response = await api.get('/users');
const data = await response.json();
post
Makes a POST request.
async post<T>(path: string, data: any | Record<string, any>, options?: IOption): Promise<Response>
Example:
const response = await api.post('/users', { name: 'John Doe' });
const result = await response.json();
put
Makes a PUT request.
async put<T>(path: string, data: any | Record<string, any>, options?: IOption): Promise<Response>
Example:
const response = await api.put('/users/1', { name: 'Jane Doe' });
const result = await response.json();
delete
Makes a DELETE request.
async delete(path: string, options?: IOption): Promise<Response>
Example:
const response = await api.delete('/users/1');
json
Makes a request and parses the response as JSON.
async json<T>(path: string, options?: Record<string, any>): Promise<T>
Example:
const data = await api.json<User[]>('/users');
text
Makes a request and parses the response as text.
async text(path: string, options?: Record<string, any>): Promise<string>
Example:
const text = await api.text('/document');
blob
Makes a request and parses the response as a Blob
.
async blob(path: string, options?: Record<string, any>): Promise<Blob>
Example:
const blob = await api.blob('/image');
arrayBuffer
Makes a request and parses the response as an ArrayBuffer
.
async arrayBuffer(path: string, options?: Record<string, any>): Promise<ArrayBuffer>
Example:
const buffer = await api.arrayBuffer('/file');
stream
Makes a request and returns a ReadableStream
for streaming large responses.
async stream(path: string, options?: Record<string, any>): Promise<ReadableStream>
Example:
const stream = await api.stream('/large-file');
const reader = stream.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
console.log('Received chunk:', value);
}
clearCache
Clears the cache.
clearCache(): void
Example:
api.clearCache();
Examples
Example 1: Fetching Data with Retries
const api = new SimFetchX({
baseUrl: 'https://api.example.com',
retry: true,
retryNumber: 3,
});
try {
const response = await api.get('/users');
const users = await response.json();
console.log(users);
} catch (error) {
console.error('Request failed:', error);
}
Example 2: Caching Responses
const api = new SimFetchX({
baseUrl: 'https://api.example.com',
});
// First request (not cached)
const response1 = await api.get('/posts');
const posts1 = await response1.json();
// Second request (cached)
const response2 = await api.get('/posts');
const posts2 = await response2.json();
console.log(posts1 === posts2); // true
Example 3: Uploading Data
const api = new SimFetchX({
baseUrl: 'https://api.example.com',
});
const response = await api.post('/upload', { file: 'data' }, {
headers: {
'Content-Type': 'application/json',
},
});
console.log(await response.json());
Example 4: Streaming Large Files
const api = new SimFetchX({
baseUrl: 'https://api.example.com',
});
const stream = await api.stream('/large-file');
const reader = stream.getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
console.log('Received chunk:', value);
}
Example 5: Error Handling
const api = new SimFetchX({
baseUrl: 'https://api.example.com',
retry: true,
retryNumber: 3,
});
try {
const response = await api.get('/nonexistent-endpoint');
const data = await response.json();
} catch (error) {
if (error.status === 404) {
console.error('Resource not found');
} else {
console.error('Request failed:', error.message);
}
}
credits to: user: https://github.com/Kanekivly & user: https://github.com/Anoncomrade993 __
License
This project is licensed under the MIT License đ. See the [LICENSE](LICENSE) file for details.