Git Product home page Git Product logo

webext-storage-cache's Introduction

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 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());
})();

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)

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

key

Type: string

value

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

maxAge

Type: TimeDescriptor
Default: {days: 30}

The amount of time 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: TimeDescriptor
Default: {days: 30}

The amount of time after which the cache item will expire.

staleWhileRevalidate

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

Related

License

MIT © Federico Brigante

webext-storage-cache's People

Contributors

cheap-glitch avatar dotconnor avatar fregante avatar kidonng avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.