index.js 2.0 KB

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