Introducing Socket Firewall: Free, Proactive Protection for Your Software Supply Chain.Learn More
Socket
Book a DemoInstallSign in
Socket

@bhawneetkaur13/smart-fetch

Package Overview
Dependencies
Maintainers
0
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@bhawneetkaur13/smart-fetch

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

latest
npmnpm
Version
1.0.1
Version published
Maintainers
0
Created
Source

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:

ParameterTypeDescriptionDefault Value
urlstringThe URL to fetch.Required
optionsobjectAdditional options to pass to the native fetch function (e.g., headers, method).{}
configobjectConfiguration options for fetchUtility.{}

Config Options:

OptionTypeDescriptionDefault Value
retriesnumberNumber of retry attempts if the request fails.0
retryDelaynumberDelay between retry attempts in milliseconds.1000 (1s)
onProgressfunctionFunction called during file downloads to track progress. Receives { loaded, total }.undefined
timeoutnumberTime in milliseconds to wait before automatically aborting the request. 0 means no timeout.0
cacheDurationnumberTime in milliseconds to cache the response. After this duration, the cache expires.0 (no caching)

Returns

ReturnTypeDescription
promisePromiseA promise that resolves to the response data.
cancelfunctionA 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.

FAQs

Package last updated on 05 Oct 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts