Redis Data Cache

August 24, 2023 Updated: February 23, 2024

Redis Data Cache

Table of Contents

The Functions

Aside from cold starts, often the slowest part of an application is fetching data. Caching data requests can speed up loading times. Using an internal store is one way to do it, or you can use a Redis cache. These functions can make working with a Redis cache extremely simple.

If the Redis connection is lost or not ready, the functions will use the callback function on each call instead as a fallback to prevent the application from crashing.

Example

To show how simple these functions are to use, here is an example:

ts
import { cache, mcache, type CacheKey } from "$/server/cache";
import { prisma } from "$/server/db";

// A function which fetches data from a DB or API
export async function getModel(id: string): Model | null {
  return await prisma.model.findFirst({
    where: { id }
  });
}

// A function which checks for and returns a cache
// or calls a callback function and fetches and returns
// the result.
export async function getModelCache(id: string) {
	return await cache(() => getModel(id), ["model", id]);
	//           ^? Model | null
}

// A function which checks for and returns multiple caches
// or calls a callback function and fetches and returns the
// result for each key.
export async function getModelCaches(ids: string[]) {
  const keys: Array<CacheKey> = ids.map((id) => ["model", id]);
	return await mcache((key) => getModel(key[1]), keys);
	//           ^? Array<Model | null>
}