Skip to main content

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.

info

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. An optional time-to-live value (in seconds) can be passed, otherwise the value will never expire.

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.

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.
};