index.js 2.1 KB

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