Basic usage
This guide will show you how to use methods of the Alokai SDK module for Redis.
Install first
Before you follow this guide, make sure you have installed the module in your Alokai Storefront project.
Server-side only
Methods exposed by the module can only be used server-side. In Next, call them e.g. within getServerSideProps(). In Nuxt, call them e.g. within useAsyncData().
Accessing the SDK
Code examples in this guide will show you how to call various Redis SDK methods in the Alokai Storefront. Here's how you can access the sdk
object.
const sdk = useSdk();
Saving records in Redis
To add a new record to Redis, use the setCache() method. Specify:
- the record's key,
- the asynchronous data callback returning the actual data to be stored in the record,
- the record's time-to-live (optional),
- invalidation tags pointing to the record (optional).
const { id } = await sdk.redis.setCache({
key: 'example-key',
data: async () => ({ id: '1992695' }),
tags: (data) => ['example-tag'],
timeToLive: 60 * 60 * 24, // 1 day
});
For more examples, refer to the setCache() documentation.
Fetching records from Redis
To fetch an existing record from Redis, use the getCache() method. Specify:
- the keys of records to retrieve.
const records = await sdk.redis.getCache({
keys: ['example-key']
});
For more examples, refer to the getCache() documentation.
Saving or fetching records from Redis
The module ships with a convenient getOrSetCache() method combining the previous two. It first tries to fetch an existing record with the given key from Redis. If the record does not exist, the method adds it. Specify:
- the record's key,
- the asynchronous data callback returning the actual data to be stored in the record,
- invalidation tags pointing to the record (optional).
const { id } = await sdk.redis.getOrSetCache({
key: 'example-key',
data: async () => ({ id: '1992695' }),
});
The methods accepts the same parameters as the setCache() method. For more information about the method itself, refer to the getOrSetCache() documentation
Invalidating records in Redis
To invalidate (i.e. remove) existing Redis records, use the invalidateCache() method. Specify:
- the list of invalidation tags associated with the records you want to invalidate.
await sdk.redis.invalidateCache({ tags: ['example-tag'] });
For more examples, refer to the invalidateCache() documentation.