time-machine-js-plugin-mysql2
v1.0.0
Published
MySQL2 connection pool patcher for time-machine-js
Readme
time-machine-js-plugin-mysql2
An adapter to synchronize mysql2 promise pools with the time-machine-js and time-machine-js-plugin-express mocking flow. It automatically intercepts pool acquisitions to mock the database session's internal clock via SET TIMESTAMP = ?.
Installation
npm install time-machine-js-plugin-mysql2 time-machine-jsUsage (with Express Plugin)
If you are using the time-machine-js-plugin-express per-request integration, you should export the timeMachineStore from the Express plugin and pass it to the MySQL patcher.
This ensures that concurrent Node.js requests querying the database simultaneously are mocked perfectly in isolation without overlapping.
import mysql from "mysql2/promise";
import { patchMysql2Pool } from "time-machine-js-plugin-mysql2";
// Import the AsyncLocalStorage store exposed by the express plugin
import { timeMachineStore } from "time-machine-js-plugin-express";
const pool = mysql.createPool({
host: "localhost",
user: "root",
database: "test",
});
// Patch the pool!
patchMysql2Pool(pool, timeMachineStore);
// Now, ANY time you checkout a connection from the pool inside an Express route,
// the server will automatically execute `SET TIMESTAMP = <Target Time>` BEFORE your query runs.
export default pool;Usage (Global Only)
If you are not using Express, or are only relying on the .env fallback mapping TIME_MACHINE_TRAVEL_TO, you can simply patch the pool without providing a store. The patcher will automatically respect the global mocked state of time-machine-js.
import mysql from 'mysql2/promise';
import { patchMysql2Pool } from 'time-machine-js-plugin-mysql2';
// Requires time-machine-js to have been initialized globally!
const pool = mysql.createPool({ ... });
patchMysql2Pool(pool);Important Warning
This library hooks into pool.getConnection(). Calls routed through pool.query() internally use pool.getConnection(), meaning they are natively covered by this patch.
However, if you create a single standalone connection (e.g. mysql.createConnection()), this plugin will NOT mock it. You must use a database pool.
License
MIT
