import {RuntimeGroupConfiguration} from "./RuntimeGroupConfiguration"; import {GroupConfigurationRepository} from "../Repositories/GroupConfigurationRepository"; import {GroupModel} from "../Models/GroupModel"; import {GroupConfigurationResult, GroupConfigurationTransformers} from "./GroupConfigurationTransformers"; // @ts-ignore import setPath from 'object-path-set'; import deepmerge from "deepmerge"; import {Nullable} from "../types/Nullable"; import {isPlainObject} from "is-plain-object"; export class GroupConfigurationHandler { private static DEFAULT_CONFIGURATION: RuntimeGroupConfiguration = { channels: null, locale: new Intl.Locale('en-GB'), permissions: { allowMemberManagingPlaydates: false } } private readonly transformers: GroupConfigurationTransformers = new GroupConfigurationTransformers(); constructor( private readonly repository: GroupConfigurationRepository, private readonly group: GroupModel ) { } public saveConfiguration(path: string, value: string): void { const configuration = this.repository.findConfigurationByPath(this.group, path); if (configuration) { this.repository.update( { ...configuration, value: value } ) return; } this.repository.create({ group: this.group, key: path, value: value, }); } public getConfiguration(): RuntimeGroupConfiguration { return deepmerge(GroupConfigurationHandler.DEFAULT_CONFIGURATION, this.getDatabaseConfiguration(), { isMergeableObject: isPlainObject }); } public getConfigurationByPath(path: string): Nullable { const configuration = this.repository.findConfigurationByPath(this.group, path); if (!configuration) { return null; } return this.transformers.getValue(configuration); } private getDatabaseConfiguration(): Partial { const values = this.repository.findGroupConfigurations(this.group); const configuration: Partial = {}; values.forEach((configValue) => { const value = this.transformers.getValue(configValue); setPath(configuration, configValue.key, value); }) return configuration; } }