Cache

Cache

new Cache(id, optionsopt)

Instances of this class represent a "cache"—a synchronous key-value store. Each instance holds the settings for the cache, and provides methods for manipulating the cache and its data.

Generally you don't creates instances of Cache directly, but instead create instances of Cache via CacheFactory#createCache.

Parameters:
Name Type Attributes Description
id string

A unique identifier for the cache.

options object <optional>

Configuration options.

Properties
Name Type Attributes Default Description
cacheFlushInterval number <optional>
null

See Cache#cacheFlushInterval.

capacity number <optional>
Number.MAX_VALUE

See Cache#capacity.

deleteOnExpire string <optional>
"none"

See Cache#deleteOnExpire.

enabled boolean <optional>
true

See Cache#enabled.

maxAge number <optional>
Number.MAX_VALUE

See Cache#maxAge.

onExpire function <optional>
null

See Cache#onExpire.

recycleFreq number <optional>
1000

See Cache#recycleFreq.

storageImpl Cache~StorageImpl <optional>
null

See Cache~StorageImpl.

storageMode string <optional>
"memory"

See Cache#storageMode.

storagePrefix string <optional>
"cachefactory.caches."

See Cache#storagePrefix.

storeOnReject boolean <optional>
false

See Cache#storeOnReject.

storeOnResolve boolean <optional>
false

See Cache#storeOnResolve.

Source:
Example
import CacheFactory from 'cachefactory';

const cacheFactory = new CacheFactory();
const options = {...};
const cache = cacheFactory.createCache('my-cache', options);

cache.put('foo', 'bar');
console.log(cache.get('foo')); // "bar"

Members

(readonly) cacheFlushInterval :number|null

The interval (in milliseconds) on which the cache should remove all of its items. Setting this to null disables the interval. The default is null.

Type:
  • number | null
Default Value:
  • null
Source:
Example

Create a cache the clears itself every 15 minutes

import CacheFactory from 'cachefactory';

const cacheFactory = new CacheFactory();
const cache = cacheFactory.createCache('my-cache', {
  cacheFlushInterval: 15 * 60 * 1000
});

(readonly) capacity :number

The maximum number of items that can be stored in the cache. When the capacity is exceeded the least recently accessed item will be removed. The default is Number.MAX_VALUE.

Type:
  • number
Default Value:
  • Number.MAX_VALUE
Source:
Example

Create a cache with a capacity of 100

import CacheFactory from 'cachefactory';

const cacheFactory = new CacheFactory();
const cache = cacheFactory.createCache('my-cache', {
  capacity: 100
});

(readonly) deleteOnExpire :string

Determines the behavior of a cache when an item expires. The default is "none".

Possible values:

  • "none" - Cache will do nothing when an item expires.
  • "passive" - Cache will do nothing when an item expires. Expired items will remain in the cache until requested, at which point they are removed, and undefined is returned.
  • "aggressive" - Cache will remove expired items as soon as they are discovered.
Type:
  • string
Default Value:
  • "none"
Source:
Examples

Create a cache that deletes items as soon as they expire

import CacheFactory from 'cachefactory';

const cacheFactory = new CacheFactory();
const cache = cacheFactory.createCache('my-cache', {
  deleteOnExpire: 'aggressive'
});

Create a cache that doesn't delete expired items until they're accessed

import CacheFactory from 'cachefactory';

const cacheFactory = new CacheFactory();
const cache = cacheFactory.createCache('my-cache', {
  deleteOnExpire: 'passive'
});

(readonly) enabled :boolean

Marks whether the cache is enabled or not. For a disabled cache, Cache#put is a no-op. The default is true.

Type:
  • boolean
Default Value:
  • true
Source:
Example

Create a cache that starts out disabled

import CacheFactory from 'cachefactory';

const cacheFactory = new CacheFactory();
const cache = cacheFactory.createCache('my-cache', {
  enabled: false
});

// The cache is disabled, this is a no-op
cache.put('foo', 'bar');
console.log(cache.get('foo')); // undefined

(readonly) id :string

Then unique identifier given to this cache when it was created.

Type:
  • string
Source:

(readonly) maxAge :number

Represents how long an item can be in the cache before expires. The cache's behavior toward expired items is determined by Cache#deleteOnExpire. The default value for maxAge is Number.MAX_VALUE.

Type:
  • number
Default Value:
  • Number.MAX_VALUE
Source:
Example

Create a cache where items expire after 15 minutes

import CacheFactory from 'cachefactory';

const cacheFactory = new CacheFactory();
const cache = cacheFactory.createCache('my-cache', {
  // Items expire after 15 minutes
  maxAge: 15 * 60 * 1000
});
const cache2 = cacheFactory.createCache('my-cache2', {
  // Items expire after 15 minutes
  maxAge: 15 * 60 * 1000,
  // Expired items will only be deleted once they are accessed
  deleteOnExpire: 'passive'
});
const cache3 = cacheFactory.createCache('my-cache3', {
  // Items expire after 15 minutes
  maxAge: 15 * 60 * 1000,
  // Items will be deleted from the cache as soon as they expire
  deleteOnExpire: 'aggressive'
});

(readonly) onExpire :function

A callback to be executed when expired items are removed from the cache when the cache is in "passive" or "aggressive" mode. The default is null. See Cache~onExpireCallback for the signature of the onExpire callback.

Type:
  • function
Default Value:
  • null
Source:
See:
Example

Create a cache where items expire after 15 minutes

import CacheFactory from 'cachefactory';

const cacheFactory = new CacheFactory();
const cache = cacheFactory.createCache('my-cache', {
  // Items expire after 15 minutes
  maxAge: 15 * 60 * 1000,
  // Expired items will only be deleted once they are accessed
  deleteOnExpire: 'passive',
  // Try to rehydrate cached items as they expire
  onExpire: function (key, value, done) {
    // Do something with key and value

    // Will received "done" callback if in "passive" mode and passing
    // an onExpire option to Cache#get.
    if (done) {
      done(); // You can pass whatever you want to done
    }
  }
});

(readonly) recycleFreq :number|null

The frequency (in milliseconds) with which the cache should check for expired items. The default is 1000. The value of this interval only matters if Cache#deleteOnExpire is set to "aggressive".

Type:
  • number | null
Default Value:
  • 1000
Source:
Example

Create a cache where items expire after 15 minutes checking every 10 seconds

import CacheFactory from 'cachefactory';

const cacheFactory = new CacheFactory();
const cache = cacheFactory.createCache('my-cache', {
  // Items expire after 15 minutes
  maxAge: 15 * 60 * 1000,
  // Items will be deleted from the cache as soon as they expire
  deleteOnExpire: 'aggressive',
  // Check for expired items every 10 seconds
  recycleFreq: 10 * 1000
});

(readonly) storageMode :string

Determines the storage medium used by the cache. The default is "memory".

Possible values:

  • "memory"
  • "localStorage"
  • "sessionStorage"
Type:
  • string
Default Value:
  • "memory"
Source:
Examples

Create a cache that stores its data in localStorage

import CacheFactory from 'cachefactory';

const cacheFactory = new CacheFactory();
const cache = cacheFactory.createCache('my-cache', {
  storageMode: 'localStorage'
});

Provide a custom storage implementation

import CacheFactory from 'cachefactory';

const cacheFactory = new CacheFactory();
const cache = cacheFactory.createCache('my-cache', {
  storageMode: 'localStorage',
  storageImpl: {
    setItem: function (key, value) {
      console.log('setItem', key, value);
      localStorage.setItem(key, value);
    },
    getItem: function (key) {
      console.log('getItem', key);
      localStorage.getItem(key);
    },
    removeItem: function (key) {
      console.log('removeItem', key);
      localStorage.removeItem(key);
    }
  }
});

(readonly) storagePrefix :string

The prefix used to namespace the keys for items stored in localStorage or sessionStorage. The default is "cachefactory.caches." which is conservatively long in order any possible conflict with other data in storage. Set to a shorter value to save storage space.

Type:
  • string
Default Value:
  • "cachefactory.caches."
Source:
Example
import CacheFactory from 'cachefactory';

const cacheFactory = new CacheFactory();
const cache = cacheFactory.createCache('my-cache', {
  storageMode: 'localStorage',
  // Completely remove the prefix to save the most space
  storagePrefix: ''
});
cache.put('foo', 'bar');
console.log(localStorage.get('my-cache.data.foo')); // "bar"

(readonly) storeOnReject :boolean

If set to true, when a promise is inserted into the cache and is then rejected, then the rejection value will overwrite the promise in the cache. The default is false.

Type:
  • boolean
Default Value:
  • false
Source:

(readonly) storeOnResolve :boolean

If set to true, when a promise is inserted into the cache and is then resolved, then the resolution value will overwrite the promise in the cache. The default is false.

Type:
  • boolean
Default Value:
  • false
Source:

(inner) StorageImpl :object

Provide a custom storage medium, e.g. a polyfill for localStorage. Default: null.

Must implement:

  • setItem - Same API as localStorage.setItem(key, value)
  • getItem - Same API as localStorage.getItem(key)
  • removeItem - Same API as localStorage.removeItem(key)
Type:
  • object
Properties:
Name Type Description
setItem function

Implementation of setItem(key, value).

getItem function

Implementation of getItem(key).

removeItem function

Implementation of removeItem(key).

Source:

Methods

destroy()

Destroys this cache and all its data and renders it unusable.

Source:
Example
cache.destroy();

disable()

Disables this cache. For a disabled cache, Cache#put is a no-op.

Source:
Example
cache.disable();

enable()

Enables this cache. For a disabled cache, Cache#put is a no-op.

Source:
Example
cache.enable();

get(key, optionsopt) → {*}

Retrieve an item from the cache, it it exists.

Parameters:
Name Type Attributes Description
key string | Array.<string>

The key of the item to retrieve.

options object <optional>

Configuration options.

Properties
Name Type Attributes Description
onExpire function <optional>

TODO

Source:
Returns:

The value for the specified key, if any.

Type
*
Examples

Retrieve an item from the cache

cache.put('foo', 'bar');
cache.get('foo'); // "bar"

Retrieve a possibly expired item while in passive mode

import CacheFactory from 'cachefactory';

const cacheFactory = new CacheFactory();
const cache = cacheFactory.createCache('my-cache', {
  deleteOnExpire: 'passive',
  maxAge: 15 * 60 * 1000
});
cache.get('foo', {
  // Called if "foo" is expired
  onExpire: function (key, value) {
    // Do something with key and value
  }
});

Retrieve a possibly expired item while in passive mode with global onExpire callback

import CacheFactory from 'cachefactory';

const cacheFactory = new CacheFactory();
const cache = cacheFactory.createCache('my-cache', {
  deleteOnExpire: 'passive',
  maxAge: 15 * 60 * 1000
  onExpire: function (key, value, done) {
    console.log('Expired item:', key);
    if (done) {
      done('foo', key, value);
    }
  }
});
cache.get('foo', {
  // Called if "foo" is expired
  onExpire: function (msg, key, value) {
    console.log(msg); // "foo"
    // Do something with key and value
  }
});

info(keyopt) → {*}

Retrieve information about the whole cache or about a particular item in the cache.

Parameters:
Name Type Attributes Description
key string <optional>

If specified, retrieve info for a particular item in the cache.

Source:
Returns:

The information object.

Type
*
Examples

Retrieve info about the cache

const info = cache.info();
info.id; // "my-cache"
info.capacity; // 100
info.maxAge; // 600000
info.deleteOnExpire; // "aggressive"
info.cacheFlushInterval; // null
info.recycleFreq; // 10000
info.storageMode; // "localStorage"
info.enabled; // false
info.size; // 1234

Retrieve info about an item in the cache

const info = cache.info('foo');
info.created; // 1234567890
info.accessed; // 1234567990
info.expires; // 1234569999
info.isExpired; // false

keys() → {Array.<string>}

Retrieve a list of the keys of items currently in the cache.

Source:
Returns:

The keys of the items in the cache

Type
Array.<string>
Example
const keys = cache.keys();

keySet() → {object}

Retrieve an object of the keys of items currently in the cache.

Source:
Returns:

The keys of the items in the cache.

Type
object
Example
const keySet = cache.keySet();

put(key, value, optionsopt) → {*}

Insert an item into the cache.

Parameters:
Name Type Attributes Description
key string

The key under which to insert the item.

value *

The value to insert.

options object <optional>

Configuration options.

Properties
Name Type Attributes Description
storeOnReject boolean <optional>

See Cache#storeOnReject.

storeOnResolve boolean <optional>

See Cache#storeOnResolve.

Source:
Returns:

The inserted value.

Type
*
Example
const inserted = cache.put('foo', 'bar');

remove(key) → {*}

Remove an item from the cache.

Parameters:
Name Type Description
key string

The key of the item to remove.

Source:
Returns:

The value of the removed item, if any.

Type
*
Example
const removed = cache.remove('foo');

removeAll()

Remove all items from the cache.

Source:
Example
cache.removeAll();

removeExpired() → {object}

Remove expired items from the cache, if any.

Source:
Returns:

The expired items, if any.

Type
object
Example
const expiredItems = cache.removeExpired();

setCacheFlushInterval(cacheFlushInterval)

Update the Cache#cacheFlushInterval for the cache. Pass in null to disable the interval.

Parameters:
Name Type Description
cacheFlushInterval number | null

The new Cache#cacheFlushInterval.

Source:
Example
cache.setCacheFlushInterval(60 * 60 * 1000);

setCapacity(capacity)

Update the Cache#capacity for the cache. Pass in null to reset to Number.MAX_VALUE.

Parameters:
Name Type Description
capacity number | null

The new Cache#capacity.

Source:
Example
cache.setCapacity(1000);

setDeleteOnExpire(deleteOnExpire)

Update the Cache#deleteOnExpire for the cache. Pass in null to reset to "none".

Parameters:
Name Type Description
deleteOnExpire string | null

The new Cache#deleteOnExpire.

Source:
Example
cache.setDeleteOnExpire('passive');

setMaxAge(maxAge)

Update the Cache#maxAge for the cache. Pass in null to reset to to Number.MAX_VALUE.

Parameters:
Name Type Description
maxAge number | null

The new Cache#maxAge.

Source:
Example
cache.setMaxAge(60 * 60 * 1000);

setOnExpire(onExpire)

Update the Cache#onExpire for the cache. Pass in null to unset the global onExpire callback of the cache.

Parameters:
Name Type Description
onExpire function | null

The new Cache#onExpire.

Source:
Example
cache.setOnExpire(function (key, value, done) {
  // Do something
});

setOptions(options, strictopt)

Update multiple cache options at a time.

Parameters:
Name Type Attributes Description
options object

The options to set.

strict boolean <optional>

Reset options not passed to options to the configured defaults.

Source:
Examples
cache.setOptions({
  maxAge: 60 * 60 * 1000,
  deleteOnExpire: 'aggressive'
});

Set two options, and reset the rest to the configured defaults

cache.setOptions({
  maxAge: 60 * 60 * 1000,
  deleteOnExpire: 'aggressive'
}, true);

setRecycleFreq(recycleFreq)

Update the Cache#recycleFreq for the cache. Pass in null to disable the interval.

Parameters:
Name Type Description
recycleFreq number | null

The new Cache#recycleFreq.

Source:
Example
cache.setRecycleFreq(10000);

setStorageMode(storageMode, storageImpl)

Update the Cache#storageMode for the cache.

Parameters:
Name Type Description
storageMode string

The new Cache#storageMode.

storageImpl object

The new Cache~StorageImpl.

Source:

touch(keyopt, optionsopt)

Reset an item's age in the cache, or if key is unspecified, touch all items in the cache.

Parameters:
Name Type Attributes Description
key string <optional>

The key of the item to touch.

options object <optional>

Options to pass to Cache#put if necessary.

Source:
Example
cache.touch('foo');

values() → {array}

Retrieve the values of all items in the cache.

Source:
Returns:

The values of the items in the cache.

Type
array
Example
const values = cache.values();

Type Definitions

onExpireCallback(key, value, doneopt)

The onExpire callback.

Parameters:
Name Type Attributes Description
key string

The key of the expired item.

value *

The value of the expired item.

done function <optional>

If in "passive" mode and you pass an onExpire callback to Cache#get, then the onExpire callback you passed to Cache#get will be passed to your global onExpire callback.

Source: