@bhawneetkaur13/smart-fetch
v1.0.1
Published
fetch-utility is a lightweight JavaScript utility that enhances the native fetch API with features like retries, caching, progress monitoring, timeouts, and request cancellation. It is designed to work in both browser environments and Node.js (with polyfi
Downloads
28
Readme
Fetch Utility
fetch-utility is a lightweight JavaScript utility that enhances the native fetch API with features like retries, caching, progress monitoring, timeouts, and request cancellation. It is designed to work in both browser environments and Node.js (with polyfills).
Features
- Cross-Platform: Works in both browser and Node.js (with polyfills for fetch and AbortController).
- Retries: Automatically retries failed requests with customizable retry counts and delays.
- Caching: In-memory caching to avoid redundant network requests.
- Abort Requests: Supports request cancellation using AbortController.
- Progress Monitoring: Track the progress of large file downloads using the onProgress callback.
- Timeout Handling: Automatically abort requests that take too long to complete.
- Lightweight: No external dependencies required (for browser environments).
Installation
For Browser
npm install fetch-utility
For Node.js (with polyfills):
npm install fetch-utility node-fetch abort-controller
Node.js Setup:
const fetch = require('node-fetch');
const AbortController = require('abort-controller');
global.fetch = fetch;
global.AbortController = AbortController;
const fetchUtility = require('fetch-utility');
Usage
- Basic Fetch Request
const { promise } = fetchUtility('https://api.example.com/data');
promise
.then((data) => console.log(data))
.catch((error) => console.error(error));
- Progress Monitoring You can track the progress of large file downloads using the onProgress option. This is useful for showing a progress bar or status updates.
const { promise } = fetchUtility('https://api.example.com/large-file', {}, {
onProgress: ({ loaded, total }) => {
const percentComplete = (loaded / total) * 100;
console.log(`Download Progress: ${percentComplete}%`);
},
});
promise
.then((data) => console.log('Download complete:', data))
.catch((error) => console.error(error));
- Retry Mechanism Automatically retry failed requests with a configurable number of retries and delay between retries.
const { promise } = fetchUtility('https://api.example.com/data', {}, {
retries: 3, // Retries 3 times
retryDelay: 1000, // Wait 1 second between retries
});
promise
.then((data) => console.log('Data fetched:', data))
.catch((error) => console.error('Failed to fetch after retries:', error));
- Timeout Handling Set a timeout to automatically abort a request if it takes too long.
const { promise } = fetchUtility('https://api.example.com/data', {}, {
timeout: 5000, // Timeout after 5 seconds
});
promise
.then((data) => console.log('Data fetched:', data))
.catch((error) => console.error('Request timed out:', error));
- Canceling Requests You can cancel an ongoing request using the cancel() function returned by fetchUtility. This is useful for aborting requests when they are no longer needed, such as when navigating away from a page.
const { promise, cancel } = fetchUtility('https://api.example.com/data');
// To cancel the request:
cancel();
promise
.then((data) => console.log('This won’t be logged because the request was canceled.'))
.catch((error) => console.error('Request was canceled:', error));
- Caching Responses You can cache the responses for a specific duration using the cacheDuration option. Cached data will be returned for subsequent requests to the same URL within the cache duration.
const { promise } = fetchUtility('https://api.example.com/data', {}, {
cacheDuration: 60000, // Cache the response for 60 seconds
});
promise
.then((data) => console.log(data)) // Returns cached data if requested again within 60 seconds
.catch((error) => console.error(error));
API
fetchUtility(url, options = {}, config = {})
Parameters:
| Parameter | Type | Description | Default Value |
|------------|----------|-----------------------------------------------------------------------------------------------|-----------------|
| url
| string
| The URL to fetch. | Required |
| options
| object
| Additional options to pass to the native fetch
function (e.g., headers, method). | {}
|
| config
| object
| Configuration options for fetchUtility
. | {}
|
Config Options:
| Option | Type | Description | Default Value |
|-----------------|------------|-----------------------------------------------------------------------------------------------|-----------------|
| retries
| number
| Number of retry attempts if the request fails. | 0
|
| retryDelay
| number
| Delay between retry attempts in milliseconds. | 1000
(1s) |
| onProgress
| function
| Function called during file downloads to track progress. Receives { loaded, total }
. | undefined
|
| timeout
| number
| Time in milliseconds to wait before automatically aborting the request. 0
means no timeout. | 0
|
| cacheDuration
| number
| Time in milliseconds to cache the response. After this duration, the cache expires. | 0
(no caching)|
Returns
| Return | Type | Description |
|-----------|------------|-------------------------------------------------------------------------|
| promise
| Promise
| A promise that resolves to the response data. |
| cancel
| function
| A function to cancel the request using AbortController
. |
Example Projects
React Example with Progress Monitoring If you're using this utility in a React project and want to display progress, here's a quick example:
import React, { useState } from 'react';
import fetchUtility from 'fetch-utility';
const FileDownload = () => {
const [progress, setProgress] = useState(0);
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const handleDownload = async () => {
try {
const { promise } = fetchUtility('https://api.example.com/large-file', {}, {
onProgress: ({ loaded, total }) => {
const percentComplete = (loaded / total) * 100;
setProgress(percentComplete);
},
});
const fetchedData = await promise;
setData(fetchedData);
} catch (err) {
setError('Failed to download the file.');
}
};
return (
<div>
<h1>Download Progress: {progress}%</h1>
{data && <p>Download complete!</p>}
{error && <p>{error}</p>}
<button onClick={handleDownload}>Start Download</button>
</div>
);
};
export default FileDownload;
License
This package is licensed under the MIT License.