cached-mysql2
v1.0.0
Published
`cached-mysql2` is a drop-in replacement for `mysql2` that provides automatic, intelligent RAM caching of `SELECT` queries, along with precise cache invalidation on table updates (`INSERT`, `UPDATE`, `DELETE`, `CREATE`, etc).
Readme
cached-mysql2
cached-mysql2 is a drop-in replacement for mysql2 that provides automatic, intelligent RAM caching of SELECT queries, along with precise cache invalidation on table updates (INSERT, UPDATE, DELETE, CREATE, etc).
Installation
npm install cached-mysql2Features
- Exact drop-in replacement: Exports the exact same API as
mysql2andmysql2/promise. - Auto Caching: Automatically caches
SELECTqueries across single orJOINstatements in RAM. - Smart Invalidation: Automatically clears the relevant cache when a table is modified.
- Easy Config: Detailed fallback configurations and per-table caching allocations (Max size MB and Expiration seconds).
Usage
Simply replace your mysql2 require:
// Using callback API
const mysql = require('cached-mysql2');
// Using promise API
const promiseMysql = require('cached-mysql2/promise');When creating a connection or pool, you can pass a cacheConfig option. It supports global limits alongside per-table limits.
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
database: 'test',
cacheConfig: {
enabled: true, // true by default
sizeMB: 100, // total MB default size for tables
timeSeconds: 60, // Global time-to-live seconds
tables: {
users: { sizeMB: 50, timeSeconds: 120 },
products: { sizeMB: 200 }
}
}
});Or you can set it directly on the module before fetching connections:
mysql.setCacheConfig({
enabled: true,
sizeMB: 50,
timeSeconds: 300
});Enable/Disable per Query
You can disable caching for a specific query directly using the options object format during .query() or .execute() execution:
const [rows] = await pool.query({
sql: 'SELECT * FROM users',
cache: false // bypasses caching
});Any actions that write to standard tables (UPDATE users SET ...) will clear related caching intelligently.
