npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@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

55

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

  1. Basic Fetch Request
const { promise } = fetchUtility('https://api.example.com/data');
promise
  .then((data) => console.log(data))
  .catch((error) => console.error(error));
  1. 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));
  1. 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));
  1. 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));
  1. 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));
  1. 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.