Alokai

setCache

Add a record to Redis.

This method communicates with the Redis server directly to set a record with a given key and data. It also associates the record with tags which can be used to invalidate (delete) the record later.

Under the hood, we store one set for each tag with all its associated keys and the data as a separate record. See the examples section for more details.

Signature

declare function setCache<TData = any>(
	props: SetCacheProps<TData>
): Promise<TData>;

Parameters

NameRequiredTypeDescription
propsRequiredSetCacheProps<TData>Parameter object which can be used with this method. Refer to its type definition to learn about possible properties.

Returns

Returns the data returned by the data callback.

Referenced Types

Examples

Adding a record.

import { sdk } from '~/sdk';

const { id } = await sdk.redis.setCache({
  key: 'example-key',
  data: async () => ({ id: '1992695' }),
});

Adding a record and invalidation tags. The tags callback receives the data returned by the data callback as an argument. This way tags can be derived from some dynamic data (e.g. product IDs fetched from your commerce backend).

import { sdk } from '~/sdk';

const { id } = await sdk.redis.setCache({
  key: 'example-key',
  data: async () => ({ id: '1992695' }),
  tags: (data) => [`product-${data.id}`],
});

Adding a record and setting its time-to-live (in seconds) using the timeToLive property.

import { sdk } from '~/sdk';

const { id } = await sdk.redis.setCache({
  key: 'example-key',
  data: async () => ({ id: '1992695' }),
  timeToLive: 60 * 60 * 24, // 1 day
});

On this page