@200systems/mf-db-mysql
Version:
MySQL database client with connection pooling, migrations, and health monitoring
66 lines • 2.69 kB
JavaScript
// packages/db-mysql/src/mysql-factory.ts
import { createLogger } from '@200systems/mf-logger';
import { MySQLClient } from './client.js';
/**
* MySQL Database Factory implementation
* Singleton pattern to manage database instances across the application
*/
export class MySQLDatabaseFactory {
static instance = null;
clients = new Map();
defaultLogger;
constructor() {
this.defaultLogger = createLogger({ context: 'mysql-factory' });
}
static getInstance() {
if (!MySQLDatabaseFactory.instance) {
MySQLDatabaseFactory.instance = new MySQLDatabaseFactory();
}
return MySQLDatabaseFactory.instance;
}
getInstance(config, logger) {
const clientKey = this.generateClientKey(config);
if (this.clients.has(clientKey)) {
this.defaultLogger.debug('Reusing existing MySQL client', { key: clientKey });
return this.clients.get(clientKey);
}
const clientLogger = logger || this.defaultLogger.child('mysql-client');
const mysqlConfig = this.validateAndConvertConfig(config);
const client = new MySQLClient(mysqlConfig, clientLogger);
this.clients.set(clientKey, client);
this.defaultLogger.info('Created new MySQL client', { key: clientKey });
return client;
}
async closeInstance() {
this.defaultLogger.info('Closing all MySQL clients', { count: this.clients.size });
const closePromises = Array.from(this.clients.values()).map(client => client.close());
await Promise.all(closePromises);
this.clients.clear();
this.defaultLogger.info('All MySQL clients closed');
}
generateClientKey(config) {
return `${config.host}:${config.port}/${config.database}/${config.user}`;
}
validateAndConvertConfig(config) {
// Validate required fields
const required = ['host', 'port', 'database', 'user', 'password'];
for (const field of required) {
if (!config[field]) {
throw new Error(`Missing required configuration field: ${field}`);
}
}
// Return config with MySQL-specific defaults
return {
...config,
charset: config.charset || 'utf8mb4',
timezone: config.timezone || 'Z',
acquireTimeout: config.acquireTimeout || 60000,
timeout: config.timeout || 60000,
reconnect: config.reconnect !== false,
multipleStatements: config.multipleStatements || false,
};
}
}
// Convenience export
export const MySQLFactory = MySQLDatabaseFactory.getInstance();
//# sourceMappingURL=factory.js.map