refactor: function getConfig add cache param

This commit is contained in:
linyuchen 2024-02-20 15:51:55 +08:00
parent a4301f0b55
commit 0545bcfdab

View File

@ -1,8 +1,7 @@
import fs from "fs";
import {Config, OB11Config} from "./types"; import {Config, OB11Config} from "./types";
import {mergeNewProperties} from "./utils"; import {mergeNewProperties} from "./utils";
const fs = require("fs");
export class ConfigUtil { export class ConfigUtil {
private readonly configPath: string; private readonly configPath: string;
private config: Config | null = null; private config: Config | null = null;
@ -11,14 +10,14 @@ export class ConfigUtil {
this.configPath = configPath; this.configPath = configPath;
} }
getConfig(): Config { getConfig(cache=true) {
if (this.config) { if (this.config && cache) {
return this.config; return this.config;
} }
this.reloadConfig(); return this.reloadConfig();
return this.config;
} }
reloadConfig(): Config { reloadConfig(): Config {
let ob11Default: OB11Config = { let ob11Default: OB11Config = {
httpPort: 3000, httpPort: 3000,
@ -42,20 +41,23 @@ export class ConfigUtil {
if (!fs.existsSync(this.configPath)) { if (!fs.existsSync(this.configPath)) {
this.config = defaultConfig; this.config = defaultConfig;
return; return this.config;
} 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) {
this.config = defaultConfig;
return this.config;
} }
mergeNewProperties(defaultConfig, jsonData); mergeNewProperties(defaultConfig, jsonData);
this.checkOldConfig(jsonData.ob11, jsonData, "httpPort", "port"); this.checkOldConfig(jsonData.ob11, jsonData, "httpPort", "port");
this.checkOldConfig(jsonData.ob11, jsonData, "httpHosts", "hosts"); this.checkOldConfig(jsonData.ob11, jsonData, "httpHosts", "hosts");
this.checkOldConfig(jsonData.ob11, jsonData, "wsPort", "wsPort"); this.checkOldConfig(jsonData.ob11, jsonData, "wsPort", "wsPort");
console.log("get config", jsonData); // console.log("get config", jsonData);
return jsonData; this.config = jsonData;
return this.config;
} }
} }