Spaces:
Sleeping
Sleeping
File size: 1,353 Bytes
d6986d3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | 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;
}
}
} |