Code Monkey home page Code Monkey logo

memoized-node-fetch's Introduction

Memoized Node Fetch

All Contributors

npm GitHub Workflow Status npm

A wrapper around node-fetch (or any other fetch-like function) that returns a single promise until it resolves.

Why?

Sometimes, you have to interface with an API that doesn't respond fast enough. Moreover, you might perform the same request multiple times. So:

  • You overload the API with the same exact requests.
  • You wait for additional time during the API response.

The solution

Return the same promise for the same exact requests until they resolve. This is more useful when you interface with stateless APIs, where you just consume data.

Scenario

User (1) makes a request to the backend. The backend then performs a request to a third-party API and then before it resolves, user (2) makes another request to the backend. The backend then needs to perform the same request, as before, to the third-party API. With this package, instead of performing a new request, you can access and use the same promise for user's (1) request and have user (2) wait for the same request's resolution. This should shorten the wait time for user (2).

Usage

This API is a wrapper around node-fetch.

Install the module: $ npm i memoized-node-fetch

import memoizedNodeFetch from 'memoized-node-fetch';

const fetch = memoizedNodeFetch();

(async () => {
    const fetch1 = fetch('https://jsonplaceholder.typicode.com/todos/1');
    const fetch2 = fetch('https://jsonplaceholder.typicode.com/todos/1');

    // This should return true because both requests return the same promise.
    console.log(fetch1 === fetch2);

    const res1 = await fetch1;
    const res2 = await fetch2;

    console.log(await res1.json());
    console.log(await res2.json());
})();

FAQ

Is this a data cache?

No. This package only caches the promise until it resolves. After the promise resolves, it is removed from the cache, along with the data returned.

How do you know that two requests are the same?

The parameters of the two fetch functions are compared (the url and the RequestOptions), the specific key used for comparing the requests is:

const key = stringToHash(url.toString() + JSON.stringify(options));

The parameters of the request are hashed and stored on a map.

Can I use another fetch-like function?

Of course, you can use your own fetch like this:

function myOwnFetch(url: RequestInfo, options?: RequestInit | undefined): Promise<Response> {
    /* bla bla bla */
}

const fetch = memoizedNodeFetch(myOwnFetch);

/* Use the fetch... */

Can I have multiple promise-cache instances?

Yes! Each time you run the factory function, a new promise-cache is created.

Is this a react-query/swr equivalent?

No. For most cases, you shouldn't use this library instead of react-query or swr. Rather you could use it in tandem with those libraries by substituting the fetcher function with this. swr, although it implements caching, doesn't implement it while the fetch is loading (so if you perform the request two times, you'll get two different promises). react-query now does (v3+), but comes with a bunch of other setup and features you might not need. So if what you want is a simple way to not multi-ping with identical fetches, this package is for you.

Why you didn't use a debounce function?

  1. I don't want to do request deduplication per-se but rather I want to return the same promise for each instance of the request. That won't work easily with the debounce function.
  2. The debounce implementation of lodash/underscore, waits for a specific preset time before running the request. If my promise takes longer to resolve, then I wouldn't reap the benefits of it. In my case, I wait for the promise to resolve before making a duplicate request.

Contributors โœจ

Thanks goes to these wonderful people (emoji key):


Nikos Polykandriotis

๐Ÿ’ป

Fernando van Loenhout

๐Ÿ’ป

Bonjour Comosava

๐Ÿ“–

This project follows the all-contributors specification. Contributions of any kind welcome!

memoized-node-fetch's People

Contributors

auderephilip avatar bonjur avatar chrispanag avatar ferrybig avatar nikpolik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

memoized-node-fetch's Issues

Q: Comparison with react-query's fetchQuery?

First, thanks for creating this library. It seems potentially like exactly what I'd want.

Second, your README says that this handles a case that react-query doesn't, which is the unification of multiple ongoing fetches into the same promise. Is this different from what fetchQuery in react-query claims to do? Specifically:

...fetchQuery is async and will ensure that duplicate requests for this query are not created with useQuery instances for the same query are rendered while the data is fetching.

xref quote here

Or is it potentially that fetchQuery itself is the problem (i.e. it doesn't unify simultaneous outgoing requests into the same promise) even though it purports to do so for useQuery hooks?

Thanks for clarifying! Really appreciate the work.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.