async-call-reducer

Reduce calls using browser storage

Usage no npm install needed!

<script type="module">
  import asyncCallReducer from 'https://cdn.skypack.dev/async-call-reducer';
</script>

README

AsyncCallReducer

GitHub Workflow Status (branch) Coverage Status

The AsyncCallReducer is a function to reduce calls using browser storage. A Promise can be encapsulated, a single HTTP request will be triggered regardless of the number of calls. Concurrent calls are added on a queue and return's data are stored in the browser.

Rules:

  • The first call is granted
  • Concurrent calls are blocked and added on a queue, then execute when the first call is ready
  • Next calls get the data from the browser storage

Installation

The function is available as the async-call-reducer package name on npm and Github.

npm i --save-dev async-call-reducer
yarn add --dev async-call-reducer

Environment

AsyncCallReducer was built for Node.js >=12.

Demo

The project includes an example of an implementation of AsyncCallReducer in the directory ./demo/.

Usage

Imagine the following function to get data from an API. Each call will trigger an HTTP request.

async function getData() {
  const data = await fetch('https://swapi.dev/api/people/?page=1');
  return await data.json();
}

By wrapping the function with the AsyncCallReducer, a single HTTP request will be triggered. Other calls will return exactly the same value, either from the storage or from the queue if the calls was concurrent.

async function getData() {
+   return await asyncCallReducer({
+       key: 'swapi',
+       callback: async () => {
            const data = await fetch('https://swapi.dev/api/people/?page=1');
            return await data.json();
+        }
+    });
}

Parameters

key

string = asyncCallReducer

Tells to the function the storage key used as a prefix. Following keys will be created:

  • asyncCallReducerData: Stored data
  • asyncCallReducerLoading: Blocker for concurrent calls
asyncCallReducer({
  key: 'swapi'
});

storage

string = sessionStorage

Tells to the function which browser storage method to use (sessionStorage|localStorage).

asyncCallReducer({
  storage: 'localStorage'
});

callback

Promise

Tells the function the promise to be executed.

💡 Keep the async keyword, the callback function must returns a Promise.

asyncCallReducer({
  callback: async () => {
    // Request data from an API and return data here
  }
});

Licence

AsyncCallReducer is licensed under the MIT License.

Created with ♥ by @yoriiis.