UNPKG

@anyme/anymejs

Version:
92 lines (88 loc) 2.86 kB
'use strict'; var typeorm = require('typeorm'); var index = require('../utils/index.js'); class DBManager { logger; dataSourceMap = new Map(); constructor(logger, config) { this.logger = logger; this.init(config); } init(config) { if (!config.enable || this.dataSourceMap.size !== 0) return; if (!index.isEmpty(config.client)) this.set("default", config.client); if (!index.isEmpty(config.clients)) { Object.entries(config.clients).forEach(([key, opt]) => { if ("default" in config && !index.isEmpty(config.default)) opt = index.deepMerge(config.default, opt); this.set(key, opt); }); } } set(key, opt) { const client = this.createClient(opt); if (client) this.dataSourceMap.set(key, client); } createClient(opt) { try { return new typeorm.DataSource(opt); } catch (error) { this.logger.error("❌ Failed to create db client:", error); return undefined; } } async connectAll() { if (this.dataSourceMap.size === 0) return []; return index.all(this.dataSourceMap, ([key, client]) => this.connectClient(client, key)); } async connectClient(client, key) { try { await client.initialize(); this.logger.info(`✅ Database client "${key}" initialized successfully`); } catch (error) { this.logger.error(`❌ Failed to initialize Database client "${key}":`, error); throw error; } } get(name) { const client = this.dataSourceMap.get(name ?? "default"); if (client) return client; else throw new Error(`Database client "${name ?? "default"}" not found`); } getAll() { return new Map(this.dataSourceMap); } async close(name) { const client = this.dataSourceMap.get(name ?? "default"); if (!client) return; await client.destroy(); this.dataSourceMap.delete(name ?? "default"); this.logger.debug(`✅ Database connection closed: ${name}`); } async closeAll() { if (this.dataSourceMap.size === 0) return; const closePromises = []; this.dataSourceMap.forEach((client, key) => { closePromises.push(new Promise((resolve) => { client.destroy().finally(() => { this.dataSourceMap.delete(key); resolve(); }); })); }); await Promise.all(closePromises); this.logger.info("✅ All database connections closed"); } } exports.DBManager = DBManager; //# sourceMappingURL=db.js.map