Map-like promised cache storage with expiration. WebExtensions module for Chrome, Firefox, Safari
This module works on content scripts, background pages and option pages.
You can download the standalone bundle and include it in your manifest.json
.
Or use npm
:
npm install --save webext-storage-cache
// This module is only offered as a ES Module
import storageCache from 'webext-storage-cache';
This module requires the storage
permission and it’s suggested to also use alarms
to safely schedule cache purging:
/* manifest.json */
{
"permissions": [
"storage",
"alarms"
],
"background": {
"scripts": [
/* Remember to include/import it in the background to enable expired cache purging */
"webext-storage-cache.js"
]
}
}
import cache from 'webext-storage-cache';
(async () => {
if (!await cache.has('unique')) {
const cachableItem = await someFunction();
await cache.set('unique', cachableItem, {
days: 3
});
}
console.log(await cache.get('unique'));
})();
The same code could also be written more effectively with cache.function
:
import cache from 'webext-storage-cache';
const cachedFunction = cache.function(someFunction, {
maxAge: {
days: 3
},
cacheKey: () => 'unique'
});
(async () => {
console.log(await cachedFunction());
})();
Similar to a Map()
, but all methods a return a Promise
. It also has a memoization method that hides the caching logic and makes it a breeze to use.
Checks if the given key is in the cache, returns a boolean
.
const isCached = await cache.has('cached-url');
// true or false
Type: string
Returns the cached value of key if it exists and hasn't expired, returns undefined
otherwise.
const url = await cache.get('cached-url');
// It will be `undefined` if it's not found.
Type: string
Caches the given key and value for a given amount of time. It returns the value itself.
const info = await getInfoObject();
await cache.set('core-info', info); // Cached for 30 days by default
Type: string
Type: string | number | boolean
or array | object
of those three types.
undefined
will remove the cached item. For this purpose it's best to use cache.delete(key)
instead
Type: TimeDescriptor
Default: {days: 30}
The amount of time after which the cache item will expire.
Deletes the requested item from the cache.
await cache.delete('cached-url');
Type: string
Deletes the entire cache.
await cache.clear();
Caches the return value of the function based on the cacheKey
. It works similarly to lodash.memoize
:
async function getHTML(url, options) {
const response = await fetch(url, options);
return response.text();
}
const cachedGetHTML = cache.function(getHTML);
const html = await cachedGetHTML('https://google.com', {});
// The HTML of google.com will be saved with the key 'https://google.com'
const freshHtml = await cachedGetHTML.fresh('https://google.com', {});
// Escape hatch to ignore memoization and force a refresh of the cache
Type: async function
that returns a cacheable value.
Returning undefined
will skip the cache, just like cache.set()
.
Type: function
that returns a string
Default: function
that returns the first argument of the call
const cachedOperate = cache.function(operate, {
cacheKey: args => args.join(',')
});
cachedOperate(1, 2, 3);
// The result of `operate(1, 2, 3)` will be stored in the key '1,2,3'
// Without a custom `cacheKey`, it would be stored in the key '1'
Type: TimeDescriptor
Default: {days: 30}
The amount of time after which the cache item will expire.
Type: TimeDescriptor
Default: {days: 0}
(disabled)
Specifies how much longer an item should be kept in cache after its expiration. During this extra time, the item will still be served from cache instantly, but getter
will be also called asynchronously to update the cache. A later call will return the updated and fresher item.
const cachedOperate = cache.function(operate, {
maxAge: {
days: 10
},
staleWhileRevalidate: {
days: 2
}
});
cachedOperate(); // It will run `operate` and cache it for 10 days
cachedOperate(); // It will return the cache
/* 11 days later, cache is expired, but still there */
cachedOperate(); // It will return the cache
// Asynchronously, it will also run `operate` and cache the new value for 10 more days
/* 13 days later, cache is expired and deleted */
cachedOperate(); // It will run `operate` and cache it for 10 days
Type: function
that returns a boolean
Default: () => false
You may want to have additional checks on the cached value, for example after updating its format.
async function getContent(url) {
const response = await fetch(url);
return response.json(); // For example, you used to return plain text, now you return a JSON object
}
const cachedGetContent = cache.function(getContent, {
// If it's a string, it's in the old format and a new value will be fetched and cached
shouldRevalidate: cachedValue => typeof cachedValue === 'string'
});
const json = await cachedGetHTML('https://google.com');
// The HTML of google.com will be saved with the key 'https://google.com'
- webext-detect-page - Detects where the current browser extension code is being run.
- webext-options-sync - Helps you manage and autosave your extension's options.
- webext-base-css - Extremely minimal stylesheet/setup for Web Extensions’ options pages (also dark mode)
- webext-dynamic-content-scripts - Automatically registers your content_scripts on domains added via permission.request
- More…
MIT © Federico Brigante