Avoid strings concatenation
[e-mobility-charging-stations-simulator.git] / src / utils / Configuration.ts
index f4eb39ad62ae287667e82355255a9f30ca2dbca4..b51e8ada35fac0d2cc1c72c71ce9b4f3c1b709d5 100644 (file)
@@ -3,22 +3,25 @@ import path from 'path';
 import { fileURLToPath } from 'url';
 
 import chalk from 'chalk';
+import merge from 'just-merge';
+import { WorkerChoiceStrategies } from 'poolifier';
 
-import ConfigurationData, {
-  StationTemplateUrl,
-  StorageConfiguration,
+import Constants from './Constants';
+import {
+  type ConfigurationData,
+  type StationTemplateUrl,
+  type StorageConfiguration,
   SupervisionUrlDistribution,
-  UIServerConfiguration,
-  WorkerConfiguration,
+  type UIServerConfiguration,
+  type WorkerConfiguration,
 } from '../types/ConfigurationData';
-import { EmptyObject } from '../types/EmptyObject';
-import { HandleErrorParams } from '../types/Error';
+import type { EmptyObject } from '../types/EmptyObject';
+import type { HandleErrorParams } from '../types/Error';
 import { FileType } from '../types/FileType';
 import { StorageType } from '../types/Storage';
 import { ApplicationProtocol } from '../types/UIProtocol';
 import { WorkerProcessType } from '../types/Worker';
 import WorkerConstants from '../worker/WorkerConstants';
-import Constants from './Constants';
 
 export default class Configuration {
   private static configurationFile = path.join(
@@ -58,18 +61,19 @@ export default class Configuration {
       );
     }
     let uiServerConfiguration: UIServerConfiguration = {
-      enabled: true,
+      enabled: false,
       type: ApplicationProtocol.WS,
       options: {
-        host: Constants.DEFAULT_UI_WEBSOCKET_SERVER_HOST,
-        port: Constants.DEFAULT_UI_WEBSOCKET_SERVER_PORT,
+        host: Constants.DEFAULT_UI_SERVER_HOST,
+        port: Constants.DEFAULT_UI_SERVER_PORT,
       },
     };
     if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'uiServer')) {
-      uiServerConfiguration = Configuration.deepMerge(
-        uiServerConfiguration,
-        Configuration.getConfig().uiServer
-      );
+      uiServerConfiguration = merge(uiServerConfiguration, Configuration.getConfig().uiServer);
+    }
+    if (Configuration.isCFEnvironment() === true) {
+      delete uiServerConfiguration.options.host;
+      uiServerConfiguration.options.port = parseInt(process.env.PORT);
     }
     return uiServerConfiguration;
   }
@@ -212,7 +216,8 @@ export default class Configuration {
       )
         ? Configuration.getConfig().workerPoolMaxSize
         : WorkerConstants.DEFAULT_POOL_MAX_SIZE,
-      poolStrategy: Configuration.getConfig().workerPoolStrategy,
+      poolStrategy:
+        Configuration.getConfig().workerPoolStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN,
     };
     if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'worker')) {
       workerConfiguration = { ...workerConfiguration, ...Configuration.getConfig().worker };
@@ -239,10 +244,18 @@ export default class Configuration {
       : true;
   }
 
-  static getLogMaxFiles(): number {
-    return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logMaxFiles')
-      ? Configuration.getConfig().logMaxFiles
-      : 7;
+  static getLogMaxFiles(): number | string | undefined {
+    return (
+      Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logMaxFiles') &&
+      Configuration.getConfig().logMaxFiles
+    );
+  }
+
+  static getLogMaxSize(): number | string | undefined {
+    return (
+      Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logMaxFiles') &&
+      Configuration.getConfig().logMaxSize
+    );
   }
 
   static getLogLevel(): string {
@@ -298,7 +311,7 @@ export default class Configuration {
   }
 
   private static logPrefix(): string {
-    return new Date().toLocaleString() + ' Simulator configuration |';
+    return `${new Date().toLocaleString()} Simulator configuration |`;
   }
 
   private static warnDeprecatedConfigurationKey(
@@ -315,13 +328,13 @@ export default class Configuration {
     ) {
       console.error(
         chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage in section '${sectionName}'${
-          logMsgToAppend && '. ' + logMsgToAppend
+          logMsgToAppend && `. ${logMsgToAppend}`
         }}`
       );
     } else if (!Configuration.isUndefined(Configuration.getConfig()[key])) {
       console.error(
         chalk`{green ${Configuration.logPrefix()}} {red Deprecated configuration key '${key}' usage${
-          logMsgToAppend && '. ' + logMsgToAppend
+          logMsgToAppend && `. ${logMsgToAppend}`
         }}`
       );
     }
@@ -372,8 +385,11 @@ export default class Configuration {
     }
   }
 
+  private static isCFEnvironment(): boolean {
+    return process.env.VCAP_APPLICATION !== undefined;
+  }
+
   private static getDefaultPerformanceStorageUri(storageType: StorageType) {
-    const SQLiteFileName = `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`;
     switch (storageType) {
       case StorageType.JSON_FILE:
         return `file://${path.join(
@@ -383,40 +399,13 @@ export default class Configuration {
       case StorageType.SQLITE:
         return `file://${path.join(
           path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../'),
-          SQLiteFileName
+          `${Constants.DEFAULT_PERFORMANCE_RECORDS_DB_NAME}.db`
         )}`;
       default:
         throw new Error(`Performance storage URI is mandatory with storage type '${storageType}'`);
     }
   }
 
-  private static isObject(item): boolean {
-    return item && typeof item === 'object' && Array.isArray(item) === false;
-  }
-
-  private static deepMerge(target: object, ...sources: object[]): object {
-    if (!sources.length) {
-      return target;
-    }
-    const source = sources.shift();
-
-    if (Configuration.isObject(target) && Configuration.isObject(source)) {
-      for (const key in source) {
-        if (Configuration.isObject(source[key])) {
-          if (!target[key]) {
-            Object.assign(target, { [key]: {} });
-          }
-          // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
-          Configuration.deepMerge(target[key], source[key]);
-        } else {
-          // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
-          Object.assign(target, { [key]: source[key] });
-        }
-      }
-    }
-    return Configuration.deepMerge(target, ...sources);
-  }
-
   private static objectHasOwnProperty(object: unknown, property: string): boolean {
     return Object.prototype.hasOwnProperty.call(object, property) as boolean;
   }
@@ -432,28 +421,22 @@ export default class Configuration {
     error: NodeJS.ErrnoException,
     params: HandleErrorParams<EmptyObject> = { throwError: true }
   ): void {
-    const prefix = logPrefix.length !== 0 ? logPrefix + ' ' : '';
-    if (error.code === 'ENOENT') {
-      console.error(
-        chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' not found: '),
-        error
-      );
-    } else if (error.code === 'EEXIST') {
-      console.error(
-        chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' already exists: '),
-        error
-      );
-    } else if (error.code === 'EACCES') {
-      console.error(
-        chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' access denied: '),
-        error
-      );
-    } else {
-      console.error(
-        chalk.green(prefix) + chalk.red(fileType + ' file ' + filePath + ' error: '),
-        error
-      );
+    const prefix = logPrefix.trim().length !== 0 ? `${logPrefix} ` : '';
+    let logMsg: string;
+    switch (error.code) {
+      case 'ENOENT':
+        logMsg = `${fileType} file ${filePath} not found: `;
+        break;
+      case 'EEXIST':
+        logMsg = `${fileType} file ${filePath} already exists: `;
+        break;
+      case 'EACCES':
+        logMsg = `${fileType} file ${filePath} access denied: `;
+        break;
+      default:
+        logMsg = `${fileType} file ${filePath} error: `;
     }
+    console.error(`${chalk.green(prefix)}${chalk.red(logMsg)}`, error);
     if (params?.throwError) {
       throw error;
     }