0.3.2 • Published 1 year ago
@rschubkegel/datacache v0.3.2
datacache
This package is intended for use with web apps that do the following:
- Fetch a significant amount of data from APIs
- Perform multiple modifications to that data before saving
- Require data to be persistent between page navigation (or browser sessions)
This package uses chunks to split data into collections. This reduces read/write overhead when only modifying small portions of a large collection of data.
For example, you may have a book writing web app where each chapter is saved in the cache as its own chunk.
Installation
Install via npm:
npm i @rschubkegel/datacache
Install via yarn:
yarn add @rschubkegel/datacache
Usage
Import & setup
import DataCache from '@rschubkegel/datacache';
const myDataCache = new DataCache(
getData, // typically GET request
putData, // typically PUT request
deleteData, // typically DELETE
'my-data', // prefix for keys in storage where data saved
window.sessionStorage // can by any object with Storage interface
);
Fetch data
// first call fetches data from API
await myDataCache
.getChunk('first-item')
.then(data => console.log('Data received:', data));
// second call (and subsequent calls) gets data from cache
let data = await myDataCache.getChunk('first-item');
Modify & save data
// data can be saved to local cache to reduce API calls
myDataCache.saveLocalChunk('first-item', {...data, newProperty: 'Hello world!'});
// user can freely navigate to & from other pages
// without losing the changes saved locally
window.location.replace('/other-page');
window.location.replace('/original-page');
// when all modifications have completed, the data can be
// saved back to the server (only requires one API call!)
myDataCache.saveChunk('first-item', data);