Cache

The Cache class provides a simple API to temporarily store and retrieve data. Caching is a powerful technique to improve the performance of your application by avoiding repeated expensive operations, such as database queries or external API calls.

Initialization

By default, the Cache class uses an in-memory store. You can optionally type the data it will store using TypeScript generics.

import { Cache } from "@harpiats/core";

// Create a cache instance that stores strings
const myCache = new Cache<string>();

Custom Stores

Just like the Session class, the Cache class accepts a custom store that implements the Store interface. This is crucial for production environments where you might want to use Redis or Memcached.

import { RedisStore } from "./my-custom-store";

const redisCache = new Cache({
  store: new RedisStore()
});

For a detailed guide on how to implement custom storage engines, please refer to the Stores documentation.

Basic Usage

The Cache class provides three primary asynchronous methods: set, get, and delete.

set(key: string, value: T)

Stores a value in the cache under the specified key.

app.post("/calculate", async (req, res) => {
  const result = "expensive calculation result";
  
  // Store the result in cache
  await myCache.set("calc_result", result);
  
  res.send("Calculated and cached!");
});

get(key: string)

Retrieves a value from the cache. Returns undefined if the key does not exist.

app.get("/calculate", async (req, res) => {
  // Try to get the result from the cache first
  const cachedResult = await myCache.get("calc_result");
  
  if (cachedResult) {
    return res.send(`From cache: ${cachedResult}`);
  }
  
  res.send("Not found in cache");
});

delete(key: string)

Removes a specific key and its value from the cache.

app.delete("/calculate/cache", async (req, res) => {
  await myCache.delete("calc_result");
  
  res.send("Cache cleared for this key");
});

In-Memory Limitations

The default MemoryStore keeps data in the RAM of the running Bun process. If the server restarts, all cached data is lost. It also cannot be shared across multiple horizontal instances (e.g., in a load-balanced environment).