index.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. const _ = require('lodash');
  2. const fs = require('fs-extra');
  3. const branchFilename = __dirname + '/application_env';
  4. const propsToSave = [
  5. 'accessPassword',
  6. 'loggingEnabled',
  7. 'maxFilesDirSize',
  8. 'queryCacheEnabled',
  9. 'cacheCleanInterval',
  10. 'lowMemoryMode',
  11. 'server',
  12. ];
  13. let instance = null;
  14. //singleton
  15. class ConfigManager {
  16. constructor() {
  17. if (!instance) {
  18. this.inited = false;
  19. instance = this;
  20. }
  21. return instance;
  22. }
  23. async init() {
  24. if (this.inited)
  25. throw new Error('already inited');
  26. this.branch = 'production';
  27. try {
  28. await fs.access(branchFilename);
  29. this.branch = (await fs.readFile(branchFilename, 'utf8')).trim();
  30. } catch (err) {
  31. //
  32. }
  33. process.env.NODE_ENV = this.branch;
  34. this.branchConfigFile = __dirname + `/${this.branch}.js`;
  35. this._config = require(this.branchConfigFile);
  36. await fs.ensureDir(this._config.dataDir);
  37. this._userConfigFile = `${this._config.dataDir}/config.json`;
  38. this.inited = true;
  39. }
  40. get config() {
  41. if (!this.inited)
  42. throw new Error('not inited');
  43. return _.cloneDeep(this._config);
  44. }
  45. set config(value) {
  46. Object.assign(this._config, value);
  47. }
  48. get userConfigFile() {
  49. return this._userConfigFile;
  50. }
  51. set userConfigFile(value) {
  52. if (value)
  53. this._userConfigFile = value;
  54. }
  55. async load() {
  56. if (!this.inited)
  57. throw new Error('not inited');
  58. if (!await fs.pathExists(this.userConfigFile)) {
  59. await this.save();
  60. return;
  61. }
  62. const data = await fs.readFile(this.userConfigFile, 'utf8');
  63. this.config = JSON.parse(data);
  64. }
  65. async save() {
  66. if (!this.inited)
  67. throw new Error('not inited');
  68. const dataToSave = _.pick(this._config, propsToSave);
  69. await fs.writeFile(this.userConfigFile, JSON.stringify(dataToSave, null, 4));
  70. }
  71. }
  72. module.exports = ConfigManager;