From 6e9704443751c7eebdeed0295120efc707c7f16e Mon Sep 17 00:00:00 2001 From: Disy Date: Mon, 19 Feb 2024 23:05:44 +0800 Subject: [PATCH] feat: cache config --- src/common/config.ts | 37 +++++++++++++++++++++++++------------ 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/src/common/config.ts b/src/common/config.ts index 762a04b..d595780 100644 --- a/src/common/config.ts +++ b/src/common/config.ts @@ -3,13 +3,27 @@ import {Config} from "./types"; const fs = require("fs"); export class ConfigUtil { - configPath: string; + private readonly configPath: string; + private config: Config | null = null; constructor(configPath: string) { this.configPath = configPath; } getConfig(): Config { + if (this.config) { + return this.config; + } + + this.reloadConfig(); + } + + setConfig(config: Config) { + this.config = config; + fs.writeFileSync(this.configPath, JSON.stringify(config, null, 2), "utf-8"); + } + + reloadConfig() { let defaultConfig: Config = { httpPort: 3000, httpHosts: [], @@ -20,36 +34,35 @@ export class ConfigUtil { debug: false, log: false, reportSelfMessage: false - } + }; + if (!fs.existsSync(this.configPath)) { return defaultConfig } else { const data = fs.readFileSync(this.configPath, "utf-8"); let jsonData: Config = defaultConfig; try { - jsonData = JSON.parse(data) + jsonData = JSON.parse(data); } catch (e) {} + if (!jsonData.httpHosts) { - jsonData.httpHosts = [] + jsonData.httpHosts = []; } if (!jsonData.wsHosts) { - jsonData.wsHosts = [] + jsonData.wsHosts = []; } if (!jsonData.wsPort) { - jsonData.wsPort = 3001 + jsonData.wsPort = 3001; } if (!jsonData.httpPort) { - jsonData.httpPort = 3000 + jsonData.httpPort = 3000; } if (!jsonData.token) { - jsonData.token = "" + jsonData.token = ""; } + return jsonData; } } - - setConfig(config: Config) { - fs.writeFileSync(this.configPath, JSON.stringify(config, null, 2), "utf-8") - } }