{"id":16414,"library":"koishi-plugin-cache-database","title":"Koishi Database Cache Plugin","description":"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.","status":"active","version":"2.1.0","language":"javascript","source_language":"en","source_url":"https://github.com/koishijs/cache","tags":["javascript","bot","chatbot","koishi","plugin","cache","client","storage","typescript"],"install":[{"cmd":"npm install koishi-plugin-cache-database","lang":"bash","label":"npm"},{"cmd":"yarn add koishi-plugin-cache-database","lang":"bash","label":"yarn"},{"cmd":"pnpm add koishi-plugin-cache-database","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core Koishi framework, this package is a plugin for Koishi.","package":"koishi","optional":false}],"imports":[{"note":"The core Koishi context object, essential for plugin development and interaction.","symbol":"Context","correct":"import { Context } from 'koishi'"},{"note":"Type definition for the plugin's configuration options.","symbol":"Config","correct":"import { Config } from 'koishi-plugin-cache-database'"},{"note":"Most Koishi plugins export their main application function as a default export or a named 'plugin' constant.","wrong":"import { apply } from 'koishi-plugin-cache-database'","symbol":"plugin","correct":"import plugin from 'koishi-plugin-cache-database'"}],"quickstart":{"code":"import { Context, Schema } from 'koishi';\nimport databaseCachePlugin from 'koishi-plugin-cache-database';\nimport sqlitePlugin from '@koishijs/plugin-database-sqlite'; // Example database plugin\n\n// Define the Koishi application context\nconst app = new Context();\n\n// Register a database plugin first, as cache-database relies on it.\n// Ensure your SQLite database file path is correct.\napp.plugin(sqlitePlugin, {\n  path: './data/koishi-cache.db'\n});\n\n// Register the database cache plugin\napp.plugin(databaseCachePlugin, {\n  // Optional: configure cache expiration or other database-specific settings\n  maxAge: 1000 * 60 * 60 * 24 // Cache items expire after 24 hours\n});\n\napp.on('ready', async () => {\n  console.log('Koishi application is ready.');\n\n  // Example usage of the cache service\n  const cacheKey = 'my-important-data';\n  const cacheValue = { message: 'Hello from cache!' };\n  const ttl = 1000 * 60 * 5; // Cache for 5 minutes\n\n  await app.cache.set(cacheKey, cacheValue, ttl);\n  console.log(`Set cache key '${cacheKey}' with value:`, await app.cache.get(cacheKey));\n\n  // Test retrieving non-existent key\n  console.log('Non-existent key:', await app.cache.get('non-existent-key'));\n\n  // Test cache expiration (demonstrative, would need time to pass)\n  // setTimeout(async () => {\n  //   console.log('After expiration (approx):', await app.cache.get(cacheKey));\n  // }, ttl + 1000);\n});\n\n// Start the Koishi application (this would typically be in your main index.ts)\napp.start().catch(err => {\n  console.error('Failed to start Koishi:', err);\n  process.exit(1);\n});","lang":"typescript","description":"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."},"warnings":[{"fix":"Upgrade your `koishi` dependency to `^4.10.0` or the latest v4.x release.","message":"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.","severity":"breaking","affected_versions":"<4.10.0"},{"fix":"Install a suitable Koishi database plugin (e.g., `npm i @koishijs/plugin-database-sqlite`) and apply it to your Koishi context before `koishi-plugin-cache-database`.","message":"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.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Monitor database performance, ensure proper indexing for cache tables, and consider using a high-performance database solution for production environments.","message":"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.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Refer to Koishi v4 migration guides for specific `user` and `channel` related caching and data access patterns. Use the generic `ctx.cache` methods provided by this plugin for custom caching needs.","message":"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.","severity":"deprecated","affected_versions":">=4.0.0 of Koishi"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Run `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.","cause":"The package was not correctly installed or not listed in `koishi.yml` or the main application entry point.","error":"Error: Plugin 'koishi-plugin-cache-database' is not found."},{"fix":"Ensure a compatible Koishi database plugin (e.g., `@koishijs/plugin-database-sqlite`) is installed and applied to the context *before* `koishi-plugin-cache-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.","error":"TypeError: Cannot read properties of undefined (reading 'database')"},{"fix":"Verify that `app.plugin(databaseCachePlugin, config)` is correctly invoked in your Koishi application's setup, and that no errors occurred during its registration.","cause":"The `koishi-plugin-cache-database` plugin was not successfully applied to the Koishi context, or the `cache` service was not properly registered.","error":"TypeError: app.cache.set is not a function"}],"ecosystem":"npm"}