index.js 2.1 KB

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