ConnManager.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. const fs = require('fs-extra');
  2. const SqliteConnectionPool = require('./SqliteConnectionPool');
  3. const configManager = new (require('../config'))();//singleton
  4. const log = new (require('../core/AppLogger'))().log;//singleton
  5. const migrations = {
  6. 'app': require('./migrations/app'),
  7. 'readerStorage': require('./migrations/readerStorage'),
  8. };
  9. let instance = null;
  10. //singleton
  11. class ConnManager {
  12. constructor() {
  13. if (!instance) {
  14. this.inited = false;
  15. instance = this;
  16. }
  17. return instance;
  18. }
  19. async init(config) {
  20. this.config = configManager.config;
  21. this._pool = {};
  22. const force = null;//(config.branch == 'development' ? 'last' : null);
  23. for (const poolConfig of this.config.db) {
  24. const dbFileName = this.config.dataDir + '/' + poolConfig.fileName;
  25. //бэкап
  26. if (await fs.pathExists(dbFileName))
  27. await fs.copy(dbFileName, `${dbFileName}.bak`);
  28. const connPool = new SqliteConnectionPool();
  29. await connPool.open(poolConfig.connCount, dbFileName);
  30. log(`Opened database "${poolConfig.poolName}"`);
  31. //миграции
  32. const migs = migrations[poolConfig.poolName];
  33. if (migs && migs.data.length) {
  34. const applied = await connPool.migrate(migs.data, migs.table, force);
  35. if (applied.length)
  36. log(`${applied.length} migrations applied to "${poolConfig.poolName}"`);
  37. }
  38. this._pool[poolConfig.poolName] = connPool;
  39. }
  40. this.inited = true;
  41. }
  42. get pool() {
  43. return this._pool;
  44. }
  45. }
  46. module.exports = ConnManager;