JSPM

  • Created
  • Published
  • Downloads 6362
  • Score
    100M100P100Q132594F
  • License MIT

WebExtensions module: Map-like promised cache storage with expiration. Chrome and Firefox.

Package Exports

  • webext-storage-cache

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (webext-storage-cache) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

webext-storage-cache

WebExtensions module: Map-like promised cache storage with expiration. Chrome and Firefox.

This module works on content scripts, background pages and option pages.

Install

You can just download the standalone bundle (it might take a minute to download) and include the file in your manifest.json, or:

npm install --save webext-storage-cache
// This module is only offered as a ES Module
import storageCache from 'webext-storage-cache';

Usage

This module requires the storage permission:

// manifest.json
{
    "permissions": [
        "storage"
    ]
}
import cache from 'webext-storage-cache';

(async () => {
    if (!await cache.has('unique')) {
        const cachableItem = await someFunction();
        await cache.set('unique', cachableItem, 3 /* days */);
    }

    console.log(await cache.get('unique'));
})();

The same code could be also written more effectively with cache.function:

import cache from 'webext-storage-cache';

const cachedFunction = cache.function(someFunction, {
    maxAge: 3,
    cacheKey: () => 'unique'
});

(async () => {
    console.log(await cachedFunction());
})();

API

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.

cache.has(key)

Checks if the given key is in the cache, returns a boolean.

const isCached = await cache.has('cached-url');
// true or false

key

Type: string

cache.get(key)

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.

key

Type: string

cache.set(key, value, maxAge /* in days */)

Caches the given key and value for a given amount of days. It returns the value itself.

const info = await getInfoObject();
await cache.set('core-info', info); // Cached for 30 days by default

key

Type: string

value

Type: string | number | boolean or array | object of those three types.

undefined won't be cached, it's considered "no value" in the Storage API.

maxAge

Type: number
Default: 30

The number of days after which the cache item will expire.

cache.delete(key)

Deletes the requested item from the cache.

await cache.delete('cached-url');

key

Type: string

cache.clear()

Deletes the entire cache.

await cache.clear();

cache.function(getter, options)

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'

getter

Type: async function that returns a cacheable value.

Returning undefined will skip the cache, just like cache.set().

options

cacheKey

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'
maxAge

Type: number
Default: 30

The number of days after which the cache item will expire.

staleWhileRevalidate

Type: number
Default: 0 (disabled)

Specifies how many additional days 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 should return an updated and fresher item.

const cachedOperate = cache.function(operate, {
    maxAge: 10,
    staleWhileRevalidate: 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
shouldRevalidate

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'

License

MIT © Federico Brigante