Koishi Database Cache Plugin

2.1.0 · active · verified Wed Apr 22

koishi-plugin-cache-database provides a persistent caching service for Koishi chatbots, leveraging an underlying database backend to store and retrieve data. This allows bot applications to maintain state across restarts and scale more effectively than in-memory caching solutions. It is currently at version `2.1.0` and follows Koishi's rapid release cadence, which aligns with major Koishi framework updates (currently Koishi v4.x). Key differentiators include its tight integration with the Koishi `Context` system, offering a database-agnostic interface for caching while requiring a separate Koishi database plugin (e.g., SQLite, MySQL, PostgreSQL) to be configured. This plugin is part of the extensive Koishi ecosystem, which is primarily developed in TypeScript, providing strong type safety and developer tooling. Unlike simpler in-memory cache plugins, this solution ensures data persistence, making it suitable for applications requiring durable state management.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up Koishi with a SQLite database, integrate `koishi-plugin-cache-database`, and perform basic cache operations like setting and retrieving values, including optional expiration.

import { Context, Schema } from 'koishi';
import databaseCachePlugin from 'koishi-plugin-cache-database';
import sqlitePlugin from '@koishijs/plugin-database-sqlite'; // Example database plugin

// Define the Koishi application context
const app = new Context();

// Register a database plugin first, as cache-database relies on it.
// Ensure your SQLite database file path is correct.
app.plugin(sqlitePlugin, {
  path: './data/koishi-cache.db'
});

// Register the database cache plugin
app.plugin(databaseCachePlugin, {
  // Optional: configure cache expiration or other database-specific settings
  maxAge: 1000 * 60 * 60 * 24 // Cache items expire after 24 hours
});

app.on('ready', async () => {
  console.log('Koishi application is ready.');

  // Example usage of the cache service
  const cacheKey = 'my-important-data';
  const cacheValue = { message: 'Hello from cache!' };
  const ttl = 1000 * 60 * 5; // Cache for 5 minutes

  await app.cache.set(cacheKey, cacheValue, ttl);
  console.log(`Set cache key '${cacheKey}' with value:`, await app.cache.get(cacheKey));

  // Test retrieving non-existent key
  console.log('Non-existent key:', await app.cache.get('non-existent-key'));

  // Test cache expiration (demonstrative, would need time to pass)
  // setTimeout(async () => {
  //   console.log('After expiration (approx):', await app.cache.get(cacheKey));
  // }, ttl + 1000);
});

// Start the Koishi application (this would typically be in your main index.ts)
app.start().catch(err => {
  console.error('Failed to start Koishi:', err);
  process.exit(1);
});

view raw JSON →