Merge pull request #54 from disymayufei/main

增加配置文件的内存缓存机制
This commit is contained in:
linyuchen 2024-02-19 23:17:11 +08:00 committed by GitHub
commit 4e4ccf4935
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -3,13 +3,27 @@ import {Config} from "./types";
const fs = require("fs"); const fs = require("fs");
export class ConfigUtil { export class ConfigUtil {
configPath: string; private readonly configPath: string;
private config: Config | null = null;
constructor(configPath: string) { constructor(configPath: string) {
this.configPath = configPath; this.configPath = configPath;
} }
getConfig(): Config { 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 = { let defaultConfig: Config = {
httpPort: 3000, httpPort: 3000,
httpHosts: [], httpHosts: [],
@ -20,36 +34,35 @@ export class ConfigUtil {
debug: false, debug: false,
log: false, log: false,
reportSelfMessage: false reportSelfMessage: false
} };
if (!fs.existsSync(this.configPath)) { if (!fs.existsSync(this.configPath)) {
return defaultConfig return defaultConfig
} else { } else {
const data = fs.readFileSync(this.configPath, "utf-8"); const data = fs.readFileSync(this.configPath, "utf-8");
let jsonData: Config = defaultConfig; let jsonData: Config = defaultConfig;
try { try {
jsonData = JSON.parse(data) jsonData = JSON.parse(data);
} }
catch (e) {} catch (e) {}
if (!jsonData.httpHosts) { if (!jsonData.httpHosts) {
jsonData.httpHosts = [] jsonData.httpHosts = [];
} }
if (!jsonData.wsHosts) { if (!jsonData.wsHosts) {
jsonData.wsHosts = [] jsonData.wsHosts = [];
} }
if (!jsonData.wsPort) { if (!jsonData.wsPort) {
jsonData.wsPort = 3001 jsonData.wsPort = 3001;
} }
if (!jsonData.httpPort) { if (!jsonData.httpPort) {
jsonData.httpPort = 3000 jsonData.httpPort = 3000;
} }
if (!jsonData.token) { if (!jsonData.token) {
jsonData.token = "" jsonData.token = "";
} }
return jsonData; return jsonData;
} }
} }
setConfig(config: Config) {
fs.writeFileSync(this.configPath, JSON.stringify(config, null, 2), "utf-8")
}
} }