Skip to content

Cache

Cache<K, V> is a bounded LRU (Least Recently Used) cache with optional TTL expiration. It is backed by Collection internally, exposing a subset of its API focused on lifecycle management.

import { Cache } from "lunibee";
// or from the sub-package:
import { Cache } from "@lunibee/collection";
new Cache<K, V>(options?: CacheOptions)
Option Type Default Description
maxSize number Infinity Maximum number of live entries. Evicts the oldest when exceeded.
ttl number 0 (disabled) Entry lifetime in milliseconds.
sweepInterval number min(ttl, 60_000) How often the background sweeper runs.
import { Cache } from "lunibee";
const messageCache = new Cache<string, Message>({
maxSize: 500,
ttl: 5 * 60 * 1000, // 5 minutes
});

Returns a live entry, or undefined if missing or expired. Promotes accessed entries to the “most recently used” position.

const msg = messageCache.get(messageId);

Stores a value. Evicts the oldest entry when maxSize is exceeded.

messageCache.set(message.id, message);

Returns true if a live, non-expired entry exists.

if (!messageCache.has(id)) {
// fetch from API
}

Removes a single entry.

messageCache.delete(messageId);

Removes all entries.

Removes all entries matching a predicate. Returns the number removed.

const count = messageCache.invalidate((msg, id) => msg.channelId === channelId);

Manually triggers a TTL sweep, removing expired entries. Returns the count removed.

const expired = messageCache.sweep();
console.log(`Swept ${expired} expired messages.`);

Returns an array of all live values.

Returns an array of [key, value] pairs for all live entries.

Property returning the count of live entries (triggers a TTL sweep).

Stops the background sweep timer. Call when you no longer need the cache to prevent memory leaks.

process.on("SIGINT", () => {
messageCache.dispose();
process.exit(0);
});

Caching API responses

const guildPreviewCache = new Cache<string, Record<string, unknown>>({
maxSize: 100,
ttl: 10 * 60 * 1000, // 10 minutes
});
async function getGuildPreview(guildId: string) {
const cached = guildPreviewCache.get(guildId);
if (cached) return cached;
const preview = await client.fetchGuildPreview(guildId);
guildPreviewCache.set(guildId, preview);
return preview;
}

Per-channel message cache

const messageCache = new Cache<string, Message>({
maxSize: 1000,
ttl: 60 * 1000, // 60 seconds
sweepInterval: 10 * 1000, // sweep every 10s
});
client.on("messageCreate", (message) => {
messageCache.set(message.id, message);
});
client.on("messageDelete", (data) => {
messageCache.delete(data.id);
});