-
Notifications
You must be signed in to change notification settings - Fork 3
/
fileconfiguration.ts
58 lines (49 loc) · 1.83 KB
/
fileconfiguration.ts
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
import { existsSync, watchFile } from "fs";
import { WebdaError } from "../index";
import { FileUtils } from "../utils/serializers";
import ConfigurationService, { ConfigurationServiceParameters } from "./configuration";
/**
* Allow for dynamic configuration from a file
* @WebdaModda Webda/FileConfiguration
*/
export class FileConfigurationService<
T extends ConfigurationServiceParameters = ConfigurationServiceParameters
> extends ConfigurationService<T> {
/** @ignore */
async init(): Promise<this> {
// Do not call super as we diverged
if (!this.parameters.source) {
throw new WebdaError.CodeError("FILE_CONFIGURATION_SOURCE_MISSING", "Need a source for FileConfigurationService");
}
// Load it from where it should be
this.parameters.source = this._webda.getAppPath(this.parameters.source);
if (!existsSync(this.parameters.source)) {
throw new WebdaError.CodeError("FILE_CONFIGURATION_SOURCE_MISSING", "Need a source for FileConfigurationService");
}
watchFile(this.parameters.source, this.checkUpdate.bind(this));
// Add webda info
this.watch("$.services", (updates: any) => this._webda.reinit(updates));
await this.checkUpdate();
return this;
}
/**
* Load the JSON from source defined file
* @override
*/
protected async loadConfiguration(): Promise<{ [key: string]: any }> {
return FileUtils.load(this.parameters.source);
}
/**
* Read the file and store it
*/
async initConfiguration(): Promise<{ [key: string]: any }> {
this.parameters.source = this._webda.getAppPath(this.parameters.source);
/**
* Auto-generate file if missing
*/
if (!existsSync(this.parameters.source) && this.parameters.default) {
FileUtils.save(this.parameters.default, this.parameters.source);
}
return this.loadAndStoreConfiguration();
}
}