File

src/module/settings/settings.service.ts

Extends

StaticSettings

Index

Properties
Methods

Constructor

constructor(orm: MikroORM, repository: EntityRepository<Setting>, em: EntityManager)
Parameters :
Name Type Optional
orm MikroORM No
repository EntityRepository<Setting> No
em EntityManager No

Methods

Private generateDefaultSettings
generateDefaultSettings()

Generates a SettingsModel with some default values.

The defaults can be overwritten by the config file. If they are present in said file those values will be used.

Returns : Setting
Async getClientSettings
getClientSettings()

See getSettingsEntity

The current settings saved in the DB.

Async getMailingOptions
getMailingOptions()

MailingConfiguration saved in the DB or undefined if none are saved.

Private Async getSettingsEntity
getSettingsEntity()

Find the settings document in the database.

Finds and returns the SettingsDocument saved in the database. If there is more than one the first document is returned.

Returns : Promise<Setting>

SettingsDocument if there is one, undefined else.

Async onApplicationBootstrap
onApplicationBootstrap()
Decorators :
@CreateRequestContext()

Checks if there is a SettingsDocument in the database.

If there is NO settings document after module initialization a new default SettingsDocument is created.

If there is ONE nothing is done.

Returns : Promise<void>
Async setClientSettings
setClientSettings(dto: ClientSettingsDTO)

Changes the settings saved in the DB to use the new settings.

If settings does not contain a property this setting-property will be untouched (ie the previous value will be used).

Parameters :
Name Type Optional Description
dto ClientSettingsDTO No

New settings to use.

Returns : Promise<void>
Private assertConfigNoErrors
assertConfigNoErrors(errors: ValidationError[])
Inherited from StaticSettings
Defined in StaticSettings:232

Checks if the errors array is empty.

If it is not empty an exception is thrown.

Parameters :
Name Type Optional Description
errors ValidationError[] No

Array containing the validation errors.

Returns : void
Private Static assertEnvNoErrors
assertEnvNoErrors(errors: ValidationError[])
Inherited from StaticSettings
Defined in StaticSettings:207

Checks if the errors array is empty. If it is not a StartUpException with a proper message is thrown.

Parameters :
Name Type Optional Description
errors ValidationError[] No

Array containing validation errors from class-validator (or empty).

Returns : void
getAPIPrefix
getAPIPrefix()
Inherited from StaticSettings
Defined in StaticSettings:132
Returns : string

Prefix for the API path.

getConfigPath
getConfigPath()
Inherited from StaticSettings
Defined in StaticSettings:125
Returns : string

Path to the configuration folder.

getDatabaseConfiguration
getDatabaseConfiguration()
Inherited from StaticSettings
Defined in StaticSettings:59

Configuration for the database.

getDatabaseConnectionInformation
getDatabaseConnectionInformation()
Inherited from StaticSettings
Defined in StaticSettings:66

Object containing the necessary information to connect to the database.

getDatabaseSecret
getDatabaseSecret()
Inherited from StaticSettings
Defined in StaticSettings:52

Returns the encryption secret for the database.

Returns : string

Encryption secret.

getGotenbergConfiguration
getGotenbergConfiguration()
Inherited from StaticSettings
Defined in StaticSettings:79

@returns Configuration for the gotenberg instance. Can be undefined.

Configuration for the gotenberg instance. Can be undefined.

getHandbookUrl
getHandbookUrl()
Inherited from StaticSettings
Defined in StaticSettings:145
Returns : string | undefined

If configured it returns the URL to the handbook, otherwise undefined is returned.

getPathPrefix
getPathPrefix()
Inherited from StaticSettings
Defined in StaticSettings:109

Returns the prefix for the app if there is one.

If there is one any trailing '/' will be removed before returning the prefix.

Returns : string | null

Prefix for the app or null if none is provided.

Static getService
getService()
Inherited from StaticSettings
Defined in StaticSettings:43

Returns the currently active service.

If no service was previously created a new one is created and returned.

Returns : StaticSettings

Current SettingsService.

getSessionTimeout
getSessionTimeout()
Inherited from StaticSettings
Defined in StaticSettings:90

Returns the value of the sessionTimeout setting.

If no sessionTimeout configuration was provided or if the provided configuration is invalid than a default value of 120 minutes is being return.

Returns : number

The specified session timeout in minutes.

getStaticFolder
getStaticFolder()
Inherited from StaticSettings
Defined in StaticSettings:152
Returns : string

Path to the static folder.

Private getStringForError
getStringForError(error: ValidationError, depth: number)
Inherited from StaticSettings
Defined in StaticSettings:254

Converts the given ValidationError to a formatted String.

Parameters :
Name Type Optional Default value Description
error ValidationError No

Error to convert to a string.

depth number No 1

Current recursion depth. Used for appending an appropriate "\t" infront of the message.

Returns : string

String for the given ValidationError.

Private initConfig
initConfig(fileContent: string, environment: string)
Inherited from StaticSettings
Defined in StaticSettings:321

Loads the configuration from the given file content.

If the content is not a valid configuration or valid YAML an exception is thrown.

Parameters :
Name Type Optional Description
fileContent string No

Content of the config file. Needs to be a valid YAML string and must contain a valid configuration.

environment string No

Value of the NodeJS environment setting.

Parsed and validated ApplicationConfiguration.

Private loadConfigFile
loadConfigFile()
Inherited from StaticSettings
Defined in StaticSettings:289

Loads the configuration file and returns the parsed configuration.

The configuration file for the current environment gets loaded and parsed.

Parsed and validated ApplicationConfiguration.

Private loadDatabaseConfig
loadDatabaseConfig()
Inherited from StaticSettings
Defined in StaticSettings:163

Loads the configuration of the database.

This is achieved by combining the required options from the config-file and the required environment variables.

Configuration options for the database.

Private Static loadEnvironmentVariables
loadEnvironmentVariables()
Inherited from StaticSettings
Defined in StaticSettings:191

Loads the environment variables as EnvironmentConfig. If not all required variables were provided a StartUpException is thrown.

Returns : EnvironmentConfig

Valid configuration extracted from the environment variables.

Properties

Private Static Readonly API_PREFIX
Type : string
Default value : 'api'
Inherited from StaticSettings
Defined in StaticSettings:20
Protected Readonly config
Type : ApplicationConfiguration
Inherited from StaticSettings
Defined in StaticSettings:23
Private Readonly databaseConfig
Type : DatabaseConfiguration
Inherited from StaticSettings
Defined in StaticSettings:24
Private Readonly envConfig
Type : EnvironmentConfig
Inherited from StaticSettings
Defined in StaticSettings:25
Protected Readonly logger
Default value : new ConsoleLogger(StaticSettings.name)
Inherited from StaticSettings
Defined in StaticSettings:27
Private Static service
Type : StaticSettings
Default value : new StaticSettings()
Inherited from StaticSettings
Defined in StaticSettings:18
Private Static Readonly STATIC_FOLDER
Type : string
Default value : 'app'
Inherited from StaticSettings
Defined in StaticSettings:21
import { CreateRequestContext, EntityRepository, MikroORM } from '@mikro-orm/core';
import { EntityManager } from '@mikro-orm/mysql';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Inject, Injectable, OnApplicationBootstrap } from '@nestjs/common';
import { IClientSettings, IMailingSettings } from 'shared/model/Settings';
import { Setting } from '../../database/entities/settings.entity';
import { StartUpException } from '../../exceptions/StartUpException';
import { ClientSettingsDTO } from './settings.dto';
import { StaticSettings } from './settings.static';

@Injectable()
export class SettingsService extends StaticSettings implements OnApplicationBootstrap {
    constructor(
        private readonly orm: MikroORM,
        @InjectRepository(Setting)
        private readonly repository: EntityRepository<Setting>,
        @Inject(EntityManager)
        private readonly em: EntityManager
    ) {
        super();
    }

    /**
     * @returns The current settings saved in the DB.
     *
     * @see getSettingsEntity
     */
    async getClientSettings(): Promise<IClientSettings> {
        const settings = await this.getSettingsEntity();
        return settings.toDTO();
    }

    /**
     * Changes the settings saved in the DB to use the new settings.
     *
     * If `settings` does not contain a property this setting-property will be untouched (ie the previous value will be used).
     *
     * @param dto New settings to use.
     */
    async setClientSettings(dto: ClientSettingsDTO): Promise<void> {
        const settings = await this.getSettingsEntity();

        settings.updateFromDTO(dto);

        await this.em.persistAndFlush(settings);
    }

    /**
     * @returns MailingConfiguration saved in the DB or `undefined` if none are saved.
     */
    async getMailingOptions(): Promise<IMailingSettings | undefined> {
        const settings = await this.getSettingsEntity();
        return settings.mailSettings?.toDTO();
    }

    /**
     * Checks if there is a `SettingsDocument` in the database.
     *
     * If there is NO settings document after module initialization a new default `SettingsDocument` is created.
     *
     * If there is ONE nothing is done.
     */
    @CreateRequestContext()
    async onApplicationBootstrap(): Promise<void> {
        const settings = await this.repository.findOne({
            id: Setting.SETTING_ID,
        });

        if (!settings) {
            this.logger.log(
                'No settings were provided. Creating new default settings...',
                SettingsService.name
            );

            try {
                const defaults = this.generateDefaultSettings();
                this.logger.log(
                    `Default settings used: ${JSON.stringify(defaults)}`,
                    SettingsService.name
                );

                await this.em.persistAndFlush(defaults);
                this.logger.log('Default settings successfully created.', SettingsService.name);
            } catch (err) {
                throw new StartUpException('Could not create the default settings.');
            }
        }
    }

    /**
     * Find the settings document in the database.
     *
     * Finds and returns the `SettingsDocument` saved in the database. If there is more than one the first document is returned.
     *
     * @returns `SettingsDocument` if there is one, `undefined` else.
     * @throws `Error` - If there is not `SettingsDocument` saved in the database.
     */
    private async getSettingsEntity(): Promise<Setting> {
        const settings = await this.repository.findOne({
            id: Setting.SETTING_ID,
        });

        if (!settings) {
            throw new Error(
                'No settings document saved in the database. This might be due to a failed initialization.'
            );
        }

        return settings;
    }

    /**
     * Generates a `SettingsModel` with some default values.
     *
     * The defaults can be overwritten by the config file. If they are present in said file those values will be used.
     */
    private generateDefaultSettings(): Setting {
        const defaultsFromConfig = this.config.defaultSettings;
        return Setting.fromDTO(defaultsFromConfig);
    }
}

results matching ""

    No results matching ""