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