Simple caching service for frontend applications.
-
TinyCache - In-memory cache service;
-
Node-Cache - For NodeJS, but works with polyfills.
This package aims to provide a simple cache service with expiration time for browser applications, utilizing the Storage API to store the data.
This allows for a simple caching service that can be used in any browser application, without the need to install any additional dependencies, but, if needed, can be extended to use a different implementation of the default localStorage
and sessionStorage
.
You can get this package on NPM.
CommonJS:
const BrowserCache = require('@giancarl021/browser-cache');
ES Modules:
import BrowserCache from '@giancarl021/browser-cache';
The imported BrowserCache
function is used to create a new instance of the cache service. It accepts an options
parameter.
const cache = BrowserCache(options);
The options
parameter is a Partial<...>
with the following properties:
interface BrowserCacheOptions {
defaultTtl: number | null;
checkPeriod: number | null;
storageEngine: Storage;
keyPrefix: string;
}
-
defaultTtl
: The default time-to-live in seconds for the cached items. Ifnull
, the items will never expire. If0
, no items will be saved. Defaults tonull
. -
checkPeriod
: The time in seconds between each check for expired items. Ifnull
or<= 0
, the check will be performed only when theget
orhas
method is called in that specific item. Defaults tonull
. -
storageEngine
: The storage engine to use, implementation of theStorage
API. Defaults tolocalStorage
. -
keyPrefix
: The prefix to be used for the keys in the storage engine. Defaults tobrowserCache::
. If set to an empty string will affect another values stored in thestorageEngine
.
-
set
: Sets a new item in the cache.key (string)
: The key of the item;value (T)
: The value of the item;ttl (number | null)
: The time-to-live of the item in seconds. Defaults tooptions.defaultTtl
;- [Typescript only]
T (unknown)
: The type of the item to be set, defaults tounknown
.
Signature:
function set<T = unknown>(key: string, value: T, ttl?: number | null): void;
-
get
: Gets an item from the cache. Will throw an error if the item does not exist.key (string)
: The key of the item;- [Typescript only]
T (unknown)
: The type of the item to be retrieved, defaults tounknown
.
Signature:
function get<T = unknown>(key: string): T;
-
has
: Checks if an item exists in the cache.key (string)
: The key of the item;
Signature:
function has(key: string): boolean;
-
expire
: Immediately expires an item in the cache.key (string)
: The key of the item;
Signature:
function expire(key: string): void;
-
close
: Closes the cache service, clearing all the items from the storage engine and removing the periodic check if set.Signature:
function close(): void;