summary refs log tree commit diff
path: root/src/util/Config.ts
blob: c3f7b84873556ea054d6a007b5a2424513be6c7c (plain) (blame)
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import "missing-native-js-functions";
import envPaths from "env-paths";
import path from "path";
import { JSONSchemaType, ValidateFunction } from "ajv"
import fs from 'fs'
import dotProp from "dot-prop";

interface Options<T> {
	path: string;
	schemaValidator: ValidateFunction;
	schema: JSONSchemaType<T>;
}

type Deserialize<T> = (text: string) => T;

function getConfigPath(name: string, configFileName: string, extension: string): string {
	const configEnvPath = envPaths(name, { suffix: "" }).config;
	const configPath = path.resolve(configEnvPath, `${configFileName}${extension}`)
	return configPath
}

class Store<T extends Record<string, any> = Record<string, unknown>> implements Iterable<[keyof T, T[keyof T]]>{
	readonly path: string;
	readonly validator: ValidateFunction;
	readonly schema: string;

	constructor(path: string, validator: ValidateFunction, schema: JSONSchemaType<T>) {
		this.validator = validator;
		if (fs.existsSync(path)) {
			this.path = path
		} else {
			this._ensureDirectory()
		}
	}

	private readonly _deserialize: Deserialize<T> = value => JSON.parse(value);

	private _ensureDirectory(): void {
		fs.mkdirSync(path.dirname(this.path), { recursive: true })
	}

	protected _validate(data: T | unknown): void {
		const valid = this.validator(data);
		if (valid || !this.validator.errors) {
			return;
		}

		const errors = this.validator.errors.map(({ instancePath, message = '' }) => `\`${instancePath.slice(1)}\` ${message}`);
		throw new Error("The configuration schema was violated!: " + errors.join('; '))

	}

	*[Symbol.iterator](): IterableIterator<[keyof T, T[keyof T]]> {
		for (const [key, value] of Object.entries(this.store)) {
			yield [key, value]
		}
	}

	public get store(): T {
		try {
			const data = fs.readFileSync(this.path).toString();
			const deserializedData = this._deserialize(data);
			this._validate(deserializedData);
			return Object.assign(Object.create(null), deserializedData);
		} catch (error) {
			if (error == 'ENOENT') {
				this._ensureDirectory();
				throw new Error("Critical, config store does not exist, the base directory has been created, copy the necessary config files to the directory");
			}

			throw error;
		}

	}
}

class Config<T extends Record<string, any> = Record<string, unknown>> extends Store<T> implements Iterable<[keyof T, T[keyof T]]> {
	constructor(options: Readonly<Partial<Options<T>>>) {
		super(options.path!, options.schemaValidator!, options.schema!);

		this._validate(this.store);

	}

	public get<Key extends keyof T>(key: Key): T[Key];
	public get<Key extends keyof T>(key: Key, defaultValue: Required<T>[Key]): Required<T>[Key];
	public get<Key extends string, Value = unknown>(key: Exclude<Key, keyof T>, defaultValue?: Value): Value;
	public get(key: string, defaultValue?: unknown): unknown {
		return this._get(key, defaultValue);
	}

	public getAll(): unknown {
		return this.store as unknown;
	}

	private _has<Key extends keyof T>(key: Key | string): boolean {
		return dotProp.has(this.store, key as string);
	}

	private _get<Key extends keyof T>(key: Key): T[Key] | undefined;
	private _get<Key extends keyof T, Default = unknown>(key: Key, defaultValue: Default): T[Key] | Default;
	private _get<Key extends keyof T, Default = unknown>(key: Key | string, defaultValue?: Default): Default | undefined {
		if (!this._has(key)) {
			throw new Error("Tried to acess a non existant property in the config");
		}

		return dotProp.get<T[Key] | undefined>(this.store, key as string, defaultValue as T[Key]);
	}

}

export default Config;