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';34const 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';34const app = new App();5app.use(new CachePlugin({6 adapter: new RedisAdapter({7 host: 'localhost',8 port: 63799 })10}));
Basic Operations
1// Set value (1 min TTL)2await ctx.cache.set('key', { data: 1 }, 60000);34// Get value5const data = await ctx.cache.get('key');67// Delete8await ctx.cache.delete('key');910// Clear all11await 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);45// Guild namespace6await 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);67 if (hasCooldown) return ctx.reply('Come back tomorrow!');89 await ctx.cache.set(cooldownKey, true, 86400000);1011 // Update user coins using namespace12 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);1516 await ctx.reply(`100 coins added! Total: ${user.coins}`);17 }18});