Cache Plugin

discordjs-nextgen-cache is a high-performance, adapter-based caching system designed for discordjs-nextgen. It supports Memory and Redis with a simple, unified API.

Installation

1npm i discordjs-nextgen-cache

For Redis support: npm i ioredis

Setup

Basic (Memory)

1import { App } from 'discordjs-nextgen';
2import { CachePlugin, MemoryAdapter } from 'discordjs-nextgen-cache';
3
4const app = new App();
5app.use(new CachePlugin({
6 adapter: new MemoryAdapter()
7}));

Advanced (Redis)

1import { App } from 'discordjs-nextgen';
2import { CachePlugin, RedisAdapter } from 'discordjs-nextgen-cache';
3
4const app = new App();
5app.use(new CachePlugin({
6 adapter: new RedisAdapter({
7 host: 'localhost',
8 port: 6379
9 })
10}));

Basic Operations

1// Set value (1 min TTL)
2await ctx.cache.set('key', { data: 1 }, 60000);
3
4// Get value
5const data = await ctx.cache.get('key');
6
7// Delete
8await ctx.cache.delete('key');
9
10// Clear all
11await ctx.cache.clear();

Namespaces (Recommended)

Namespaces automatically prefix your keys (e.g., user:ID) to keep your cache organized and prevent collisions.

1// User namespace (auto prefixes 'user:ID')
2await ctx.cache.user.set(ctx.user.id, { coins: 100 });
3const coins = await ctx.cache.user.get(ctx.user.id);
4
5// Guild namespace
6await ctx.cache.guild.set(ctx.guild.id, { settings: true });

The wrap Method

The wrap method is the most efficient way to handle 'Cache-Aside' logic. It checks the cache first; if missing, it executes your function, stores the result, and returns it.

1const profile = await ctx.cache.wrap(`profile:${userId}`, async () => {
2 return await db.users.findUnique({ where: { id: userId } });
3}, 300000); // 5 minutes TTL

Complete Example

1app.command({
2 name: 'daily',
3 run: async (ctx) => {
4 const cooldownKey = `daily_cd:${ctx.user.id}`;
5 const hasCooldown = await ctx.cache.get(cooldownKey);
6
7 if (hasCooldown) return ctx.reply('Come back tomorrow!');
8
9 await ctx.cache.set(cooldownKey, true, 86400000);
10
11 // Update user coins using namespace
12 let user = await ctx.cache.user.get(ctx.user.id) || { coins: 0 };
13 user.coins += 100;
14 await ctx.cache.user.set(ctx.user.id, user);
15
16 await ctx.reply(`100 coins added! Total: ${user.coins}`);
17 }
18});