Cache
The Cache class provides caching capabilities that can take one of two forms: an in-memory cache or a cache backed by
a Redis instance.
Every integration hosted by Unito has access to a Redis instance which can be found using the environment variable process.env.REDIS_URL.
Methods
static create()
Takes an optional URL pointing to a Redis database. If the URL is provided, a Cache using the target Redis database will be returned, otherwise, the method will return an in-memory cache instead.
getOrFetchValue()
Returns the cached value if present, or calls the provided fetch function to compute the value, cache it for the given time-to-live value (in seconds), and return it to the caller.
getValue()
Returns the cached value, or undefined if absent.
setValue()
Sets the value for the given key, in cache, for the given time-to-live value (in seconds), which is required. With 0
the value never expires on Redis; the in-memory cache (no Redis URL) still drops it after its max age (30 minutes by
default, CACHETTE_LC_MAX_AGE in milliseconds), or sooner once it is full.
lock()
Locks the named resource for the given time-to-live in milliseconds (setValue() and getOrFetchValue() take
seconds) and returns a lock to release with cache.unlock(lock). When the resource stays held by someone else for
every attempt, it throws LockAcquisitionError, which the SDK exports. For the lock options of getOrFetchValue() and
when they throw, see the LockOptions docs in cachette.
delValue()
Removes the given key and its corresponding value from the cache.
getTtl()
Returns the remaining TTL on the entry (in miliseconds), undefined if the entry does not exist, or 0 if the entry
does not expire. That 0 is for Redis: the in-memory cache returns 0 while more than 30 minutes remain, and an entry
set with 0 counts down from its max age.
Examples
To make a cache available through your integration code base, create a file named cache.ts.
You can pass a URL pointing to a Redis database to receive a Cache connected to this database;
import { Cache } from '@unitoio/integration-sdk';
export const cache: Cache = Cache.create(process.env.REDIS_URL);
Or alternatively, you can omit the URL and receive an in-memory cache;
import { Cache } from '@unitoio/integration-sdk';
export const cache: Cache = Cache.create();
From there, your cache is available to use elsewhere in you codebase, as needed;
import { cache } from './cache.ts';
const cacheKey = 'MyGlobalyUniqueKey_xyz';
const cacheTtl = 300; // 5 mins as an example
export const getItem: GetItemHandler = async context => {
const response = await cache.getOrFetchValue(cacheKey, cacheTtl, async () => {
// Actual fetch function to use on cache miss
});
// etc.
};