Fix config change on WebUI causing hot reload in dev mode

As a side effect, hot-reloading the config is now a feature of SNS, so it's not exclusive to dev mode.
This commit is contained in:
Sainan 2024-06-15 01:09:56 +02:00
parent 9203cf297b
commit d36341c958
3 changed files with 29 additions and 15 deletions

View File

@ -1,8 +1,8 @@
import { RequestHandler } from "express";
import configFile from "@/config.json";
import { config } from "@/src/services/configService";
const getConfigDataController: RequestHandler = (_req, res) => {
res.json(configFile);
res.json(config);
};
export { getConfigDataController };

View File

@ -1,16 +1,9 @@
import { RequestHandler } from "express";
import path from "path";
import fs from "fs";
const rootDir = path.join(__dirname, "../../..");
import { updateConfig } from "@/src/services/configService";
const updateConfigDataController: RequestHandler = req => {
const updateSettingsData = req.body;
fs.writeFile(path.join(rootDir, "config.json"), updateSettingsData, function (err: any) {
if (err) {
return console.log(err);
}
});
const updateConfigDataController: RequestHandler = async (req, res) => {
await updateConfig(req.body.toString());
res.end();
};
export { updateConfigDataController };

View File

@ -1,4 +1,22 @@
import rawConfig from "@/config.json";
import path from "path";
import fs from "fs";
import fsPromises from "fs/promises";
import { logger } from "@/src/utils/logger";
const rootDir = path.join(__dirname, "../..");
const repoDir = path.basename(rootDir) == "build" ? path.join(rootDir, "..") : rootDir;
const configPath = path.join(repoDir, "config.json");
export const config: IConfig = JSON.parse(fs.readFileSync(configPath, "utf-8"));
let amnesia = false;
fs.watchFile(configPath, () => {
if (amnesia) {
amnesia = false;
} else {
logger.info("Detected a change to config.json, reloading its contents.");
Object.assign(config, JSON.parse(fs.readFileSync(configPath, "utf-8")));
}
});
interface IConfig {
mongodbUrl: string;
@ -26,4 +44,7 @@ interface ILoggerConfig {
level: string; // "fatal" | "error" | "warn" | "info" | "http" | "debug" | "trace";
}
export const config: IConfig = rawConfig;
export const updateConfig = async (data: string) => {
amnesia = true;
return await fsPromises.writeFile(configPath, data);
};