87 lines
No EOL
2.3 KiB
TypeScript
87 lines
No EOL
2.3 KiB
TypeScript
import {ConfigurationProvider} from "./ConfigurationProvider";
|
|
import {ConfigurationModel} from "../Database/Models/ConfigurationModel";
|
|
// @ts-expect-error set-path is provided
|
|
import setPath from 'object-path-set';
|
|
import deepmerge from "deepmerge";
|
|
// @ts-expect-error Any is fine
|
|
import {isPlainObject} from "is-plain-object";
|
|
import {Nullable} from "../types/Nullable";
|
|
import {ConfigurationTransformer, TransformerResults} from "./ConfigurationTransformer";
|
|
import _ from "lodash";
|
|
|
|
export enum PathConfigurationFrom {
|
|
Database,
|
|
Default
|
|
}
|
|
|
|
export type PathConfiguration = {
|
|
value: TransformerResults,
|
|
from: PathConfigurationFrom
|
|
}
|
|
|
|
export class ConfigurationHandler<
|
|
TProviderModel extends ConfigurationModel = ConfigurationModel,
|
|
TRuntimeConfiguration extends object = Record<string, string>,
|
|
> {
|
|
public readonly transformer: ConfigurationTransformer
|
|
|
|
constructor(
|
|
private readonly provider: ConfigurationProvider<TProviderModel>
|
|
) {
|
|
this.transformer = provider.getTransformer();
|
|
}
|
|
|
|
public save(path: string, value: string): void {
|
|
const configuration = this.provider.get(path);
|
|
|
|
if (configuration) {
|
|
this.provider.save({
|
|
...configuration,
|
|
value
|
|
});
|
|
|
|
return;
|
|
}
|
|
|
|
this.provider.save({
|
|
key: path,
|
|
value
|
|
});
|
|
}
|
|
|
|
public getCompleteConfiguration(): TRuntimeConfiguration {
|
|
return deepmerge(
|
|
this.provider.defaults,
|
|
this.getCompleteDatabaseConfig(),
|
|
{
|
|
isMergeableObject: isPlainObject
|
|
}
|
|
)
|
|
}
|
|
|
|
public getConfigurationByPath(path: string): PathConfiguration {
|
|
const configuration = this.provider.get(path);
|
|
if (!configuration) {
|
|
return {
|
|
value: _.get(this.provider.defaults, path, null),
|
|
from: PathConfigurationFrom.Default
|
|
};
|
|
}
|
|
|
|
return {
|
|
value: this.transformer.getValue(configuration),
|
|
from: PathConfigurationFrom.Database
|
|
};
|
|
}
|
|
private getCompleteDatabaseConfig(): Partial<TRuntimeConfiguration> {
|
|
const values = this.provider.getAll();
|
|
const configuration: Partial<TRuntimeConfiguration> = {};
|
|
|
|
values.forEach((configValue) => {
|
|
const value = this.transformer.getValue(configValue);
|
|
_.set(configuration, configValue.key, value);
|
|
})
|
|
|
|
return configuration;
|
|
}
|
|
} |