Koishi Database Cache Plugin
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
-
Error: Plugin 'koishi-plugin-cache-database' is not found.
cause The package was not correctly installed or not listed in `koishi.yml` or the main application entry point.fixRun `npm install koishi-plugin-cache-database` (or `yarn add`) and ensure the plugin is applied using `app.plugin(require('koishi-plugin-cache-database'))` or `app.plugin(pluginFromImport)` in your Koishi application. -
TypeError: Cannot read properties of undefined (reading 'database')
cause The underlying database service that `koishi-plugin-cache-database` depends on was not initialized or failed to start before the cache plugin tried to access it.fixEnsure a compatible Koishi database plugin (e.g., `@koishijs/plugin-database-sqlite`) is installed and applied to the context *before* `koishi-plugin-cache-database`. -
TypeError: app.cache.set is not a function
cause The `koishi-plugin-cache-database` plugin was not successfully applied to the Koishi context, or the `cache` service was not properly registered.fixVerify that `app.plugin(databaseCachePlugin, config)` is correctly invoked in your Koishi application's setup, and that no errors occurred during its registration.
Warnings
- breaking This plugin requires Koishi v4.10.0 or higher. Older Koishi versions will likely encounter compatibility issues or fail to load the plugin due to API changes in the core framework.
- gotcha This plugin provides a database-backed cache *service* but does not include a database *driver*. You must install and configure a separate Koishi database plugin (e.g., `@koishijs/plugin-database-sqlite`, `@koishijs/plugin-database-mysql`) *before* applying this cache plugin.
- gotcha Improper database configuration for the underlying storage (e.g., insufficient connection pool, slow I/O, unoptimized queries) can severely impact the performance of the cache service and the overall bot responsiveness.
- deprecated Koishi v4 has made significant internal changes to how user and channel data is handled, including the removal of direct `user/channel` cache access in certain contexts. While this plugin provides a general-purpose cache, direct reliance on removed Koishi internal cache mechanisms might lead to issues.
Install
-
npm install koishi-plugin-cache-database -
yarn add koishi-plugin-cache-database -
pnpm add koishi-plugin-cache-database
Imports
- Context
import { Context } from 'koishi' - Config
import { Config } from 'koishi-plugin-cache-database' - plugin
import { apply } from 'koishi-plugin-cache-database'import plugin from 'koishi-plugin-cache-database'
Quickstart
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);
});