store.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { IAPP_CONFIG } from "./interfaces";
  2. import path from 'path';
  3. import fs from 'fs/promises';
  4. export class GlobalStore {
  5. private config: IAPP_CONFIG | null;
  6. constructor (config: IAPP_CONFIG | null | undefined = null) {
  7. this.config = config
  8. }
  9. public getConfig (): IAPP_CONFIG {
  10. if (this.config === null) {
  11. throw '应用全局配置信息错误,检查应用的配置信息是否被正确获取或者后续存在非法的修改操作.'
  12. } else {
  13. return this.config;
  14. }
  15. }
  16. public async syncConfig (): Promise<IAPP_CONFIG> {
  17. const filePath = path.resolve(__dirname, '../app-config.json');
  18. const dataBuffer = await fs.readFile(filePath);
  19. const data = JSON.parse(dataBuffer.toString()) as IAPP_CONFIG;
  20. this.config = data;
  21. return data;
  22. }
  23. public async setConfig (config: IAPP_CONFIG) {
  24. const filePath = path.resolve(__dirname, '../app-config.json');
  25. await fs.writeFile(filePath, JSON.stringify(config));
  26. this.config = config
  27. }
  28. }
  29. const storeRef: { ref: GlobalStore } = {
  30. ref: new GlobalStore()
  31. };
  32. export function useGlobalStore() {
  33. return storeRef.ref;
  34. }
  35. export function updateGlobalStore (value: GlobalStore) {
  36. storeRef.ref = value;
  37. }