yamli-cache
v1.0.2
Published
A cache for Yamli to avoid remote lookups unnecessarily.
Readme
yamli-cache
A cache layer for the Yamli service to avoid unnecessary remote lookups by caching frequently requested data locally.
Features
- Caches transliteration responses from the Yamli API.
- Reduces redundant network requests by checking cached values first.
- Allows for customization with preloaded initial cache values.
Installation
# Using Bun (recommended)
bun add yamli-cache
# Or using npm
npm install yamli-cacheUsage
Initializing the Cache
To initialize the cache, use the initCache function. You can pass an initial cache value to preload any frequently requested data.
import { initCache } from 'yamli-cache';
const Yamli = {
/* Yamli object with necessary properties */
};
const initialCache = { hello: ['مرحبا', 'هلا'] };
const cache = initCache(Yamli, initialCache);Example Code
This example demonstrates how to initialize and use the cache.
// this example uses the local storage to store the cache
import { disableAnalytics, initCache } from 'yamli-cache';
const loadCache = () => JSON.parse(localStorage.getItem('yamliCache')) || {};
disableAnalytics(window.Yamli);
const cache = initCache(window.Yamli, loadCache());
// Recommendation: save your cache on exit so they can be persisted
window.addEventListener('beforeunload', () => {
const currentCache = loadCache();
// recommendation: spread the current cache with the one in storage in case user opened up your site in more than one tab so you don't accidentally lose data that was saved from another tab
localStorage.setItem('yamliCache', JSON.stringify({ ...currentCache, ...cache }));
});API Reference
initCache
Initializes a cache for Yamli requests to intercept and store responses, reducing network load.
Parameters
Yamli- The main Yamli object containing the request functions and configurations.initialValue- Optional. An initial cache to preload frequently requested data.
Returns
YamliCache- The initialized cache object that stores words and their mapped transliterations.
License
MIT
