Merge pull request #5 from DiegoMagdaleno/master
Config refactoring to be a file
This commit is contained in:
commit
ef4f32e597
BIN
package-lock.json
generated
BIN
package-lock.json
generated
Binary file not shown.
@ -30,6 +30,9 @@
|
|||||||
"@types/mongoose-autopopulate": "^0.10.1",
|
"@types/mongoose-autopopulate": "^0.10.1",
|
||||||
"@types/mongoose-lean-virtuals": "^0.5.1",
|
"@types/mongoose-lean-virtuals": "^0.5.1",
|
||||||
"@types/node": "^14.14.25",
|
"@types/node": "^14.14.25",
|
||||||
|
"ajv": "^8.5.0",
|
||||||
|
"dot-prop": "^6.0.1",
|
||||||
|
"env-paths": "^2.2.1",
|
||||||
"jsonwebtoken": "^8.5.1",
|
"jsonwebtoken": "^8.5.1",
|
||||||
"missing-native-js-functions": "^1.2.2",
|
"missing-native-js-functions": "^1.2.2",
|
||||||
"mongodb": "^3.6.6",
|
"mongodb": "^3.6.6",
|
||||||
|
|||||||
@ -1,38 +1,113 @@
|
|||||||
import { Schema, model, Types, Document } from "mongoose";
|
|
||||||
import "missing-native-js-functions";
|
import "missing-native-js-functions";
|
||||||
import db, { MongooseCache } from "./Database";
|
import envPaths from "env-paths";
|
||||||
|
import path from "path";
|
||||||
|
import { JSONSchemaType, ValidateFunction } from "ajv"
|
||||||
|
import fs from 'fs'
|
||||||
|
import dotProp from "dot-prop";
|
||||||
|
|
||||||
var Config = new MongooseCache(db.collection("config"), [], { onlyEvents: false });
|
interface Options<T> {
|
||||||
|
path: string;
|
||||||
export default {
|
schemaValidator: ValidateFunction;
|
||||||
init: async function init(defaultOpts: any = DefaultOptions) {
|
schema: JSONSchemaType<T>;
|
||||||
await Config.init();
|
|
||||||
return this.setAll(Config.data.merge(defaultOpts));
|
|
||||||
},
|
|
||||||
getAll: function get() {
|
|
||||||
return <DefaultOptions>Config.data;
|
|
||||||
},
|
|
||||||
setAll: function set(val: any) {
|
|
||||||
return db.collection("config").updateOne({}, { $set: val }, { upsert: true });
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
export const DefaultOptions = {
|
|
||||||
api: {},
|
|
||||||
gateway: {},
|
|
||||||
voice: {},
|
|
||||||
};
|
|
||||||
|
|
||||||
export interface DefaultOptions extends Document {
|
|
||||||
api?: any;
|
|
||||||
gateway?: any;
|
|
||||||
voice?: any;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ConfigSchema = new Schema({
|
type Deserialize<T> = (text: string) => T;
|
||||||
api: Object,
|
|
||||||
gateway: Object,
|
export function getConfigPathForFile(name: string, configFileName: string, extension: string): string {
|
||||||
voice: Object,
|
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;
|
||||||
|
|
||||||
export const ConfigModel = model<DefaultOptions>("Config", ConfigSchema, "config");
|
|
||||||
|
|||||||
Reference in New Issue
Block a user