Wraps any asynchronous function and provides caching of the result
pnpm install --save ceych
'use strict';
const request = require('request');
const Catbox = require('@hapi/catbox').Client;
const Redis = require('@hapi/catbox-redis');
const ceych = require('ceych').createClient({
cacheClient: new Catbox(new Redis({
port: 6379,
host: '127.0.0.1',
partition: 'cache'
})),
defaultTTL: 30
});
function loadData(cb) {
request.get('https://www.big-data.com/datum.csv', cb);
}
const loadDataCached = ceych.wrap(loadData);
const miss = loadDataCached(); // returned from the server and stored in the cache
const hit = loadDataCached(); // returned from the server and stored in the cacheCeych automatically creates cache keys based on the wrapped function's body and the arguments passed. This saves you from having to create a unique cache key every time you want the result of a function to be cached.
Return values and arguments need to be serializable to/from JSON. This means that while strings, numbers and basic objects are supported, objects with custom constructors or prototypes are not.
When using a node-statsd client, ceych will increment a counter each time there is a cache hit or miss. The following metrics are sent:
| Metric | Type | Description |
|---|---|---|
| ceych.hits | counter |
Incremented whenever there is a cache hit |
| ceych.misses | counter |
Incremented whenever there is a cache miss |
Creates a ceych client.
cacheClient- optional - A Catbox client (defaults to an in-memory client).defaultTTL- optional - The default TTL for caching in seconds (default 30).statsClient- optional - An instance of the node-statsd client
Returns a wrapped function that implements caching.
fn- An asynchronous function to be wrapped.ttl- optional - Overrides the default TTL.suffix- optional - A string appended to cache keys to differentiate between identical functions.
Invalidates the current cache entry for the given function and args combination. The function passed should be the unwrapped, initial function.
funcOrOpts- Either a function or a set of options of the format{ func: yourFunction, suffix: 'yourSuffix' }if you wish to include a suffix....args- The args that you passed to the wrapped function call which initially stored the cache entry.
Disables the use of the cache. This can be useful if you want to toggle usage of the cache for operational purposes - e.g. for operational purposes, or unit tests.
Re-enables the cache client. This can be useful if you want to toggle usage of the cache for operational purposes - e.g. for operational purposes, or unit tests.