core/src/types/config.ts

110 lines
2.5 KiB
TypeScript

import * as fs from 'fs-extra';
import { IEnvironment } from './environment';
export class Configuration {
public config: any = {};
private loaded = false;
constructor(private env: IEnvironment, private file: string, private defaults: any = {}) {}
public async load(): Promise<void> {
this.loaded = true;
if (!await fs.pathExists(this.file)) {
this.saveDefaults();
return;
}
const json = await fs.readJson(this.file);
this.config = json;
if (this.defaults) {
this.config = Object.assign({}, this.defaults, json);
}
}
public async save(): Promise<void> {
return fs.writeJson(this.file, this.config);
}
public get(key: string, defval?: any, from?: any): any {
if (!from) {
from = this.config;
}
// Recursive object traversal
if (key.indexOf('.') !== -1) {
const split = key.split('.');
const first = this.get(split[0], null, from);
if (first) {
return this.get(split.slice(1).join('.'), defval, first);
}
return defval;
}
// Array indexing
if (key.indexOf('[') !== -1 && key.indexOf(']') !== -1) {
const match = key.match(/\[(\d+)\]/i);
const realKey = key.substr(0, key.indexOf('['));
if (match != null) {
const index = parseInt(match[1], 10);
if (from[realKey]) {
return from[realKey][index];
}
}
return defval;
}
if (!from[key]) {
return defval;
}
return from[key];
}
public set(key: string, value?: any, from?: any): boolean {
if (!from) {
from = this.config;
}
// Recursive object traversal
if (key.indexOf('.') !== -1) {
const split = key.split('.');
const first = this.get(split[0], null, from);
if (first) {
return this.set(split.slice(1).join('.'), value, first);
}
return false;
}
// Array indexing
if (key.indexOf('[') !== -1 && key.indexOf(']') !== -1) {
const match = key.match(/\[(\d+)\]/i);
const realKey = key.substr(0, key.indexOf('['));
if (match != null) {
const index = parseInt(match[1], 10);
if (from[realKey]) {
from[realKey][index] = value;
}
}
return false;
}
if (!from[key]) {
return false;
}
from[key] = value;
return true;
}
public setDefaults(defconf: any): void {
this.defaults = defconf;
}
private saveDefaults(): void {
this.config = this.defaults || {};
this.save();
}
}