NSMP-Server / src /config /config.ts
Franek-Le's picture
Initial commit
d6986d3
Raw
History Blame Contribute Delete
1.35 kB
import * as fs from "fs";
import * as path from "path";
export class Config {
private readonly data: Record<string, string | object | number | []>;
constructor(data: Record<string, any>) {
this.data = data;
}
public static load(fileName = "config.json"): Config {
const configPath = Config.findConfigFile(fileName);
if (!configPath) {
throw new Error(`Could not find ${fileName}`);
}
const contents = fs.readFileSync(configPath, "utf8");
const data = JSON.parse(contents);
return new Config(data);
}
public get<T>(key: string): T {
if (!(key in this.data)) {
throw new Error(`Missing configuration key: ${key}`);
}
return this.data[key] as T;
}
public has(key: string): boolean {
return key in this.data;
}
private static findConfigFile(fileName: string): string | null {
let currentDir = process.cwd();
while (true) {
const candidate = path.join(currentDir, fileName);
if (fs.existsSync(candidate)) {
return candidate;
}
const parentDir = path.dirname(currentDir);
if (parentDir === currentDir) {
return null;
}
currentDir = parentDir;
}
}
}