refactor(configuration): Setup configuration and menu to be reuseable
This commit is contained in:
parent
863ae3fab2
commit
d46bbd84c5
21 changed files with 551 additions and 452 deletions
71
source/Configuration/ConfigurationHandler.ts
Normal file
71
source/Configuration/ConfigurationHandler.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
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";
|
||||
|
||||
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): Nullable<TransformerResults> {
|
||||
const configuration = this.provider.get(path);
|
||||
if (!configuration) {
|
||||
return;
|
||||
}
|
||||
|
||||
return this.transformer.getValue(configuration);
|
||||
}
|
||||
|
||||
private getCompleteDatabaseConfig(): Partial<TRuntimeConfiguration> {
|
||||
const values = this.provider.getAll();
|
||||
const configuration: Partial<TRuntimeConfiguration> = {};
|
||||
|
||||
values.forEach((configValue) => {
|
||||
const value = this.transformer.getValue(configValue);
|
||||
setPath(configuration, configValue.key, value);
|
||||
})
|
||||
|
||||
return configuration;
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue