From: Jérôme Benoit Date: Sun, 28 May 2023 20:33:20 +0000 (+0200) Subject: refactor(simulator): convert some class method helpers to arrow function X-Git-Tag: v1.2.15~17 X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=fa5995d65e5084241af14d0ab7453fbb2fc9d8a6;p=e-mobility-charging-stations-simulator.git refactor(simulator): convert some class method helpers to arrow function Signed-off-by: Jérôme Benoit --- diff --git a/src/charging-station/Bootstrap.ts b/src/charging-station/Bootstrap.ts index 802a9445..35f67a95 100644 --- a/src/charging-station/Bootstrap.ts +++ b/src/charging-station/Bootstrap.ts @@ -22,7 +22,14 @@ import { type StationTemplateUrl, type Statistics, } from '../types'; -import { Configuration, Constants, ErrorUtils, Utils, logger } from '../utils'; +import { + Configuration, + Constants, + Utils, + handleUncaughtException, + handleUnhandledRejection, + logger, +} from '../utils'; import { type MessageHandler, type WorkerAbstract, WorkerFactory } from '../worker'; const moduleName = 'Bootstrap'; @@ -51,8 +58,8 @@ export class Bootstrap extends EventEmitter { process.on(signal, this.gracefulShutdown); } // Enable unconditionally for now - ErrorUtils.handleUnhandledRejection(); - ErrorUtils.handleUncaughtException(); + handleUnhandledRejection(); + handleUncaughtException(); this.initializedCounters = false; this.started = false; this.initializeCounters(); diff --git a/src/charging-station/ChargingStation.ts b/src/charging-station/ChargingStation.ts index 94447bb3..28138afb 100644 --- a/src/charging-station/ChargingStation.ts +++ b/src/charging-station/ChargingStation.ts @@ -89,14 +89,14 @@ import { Configuration, Constants, DCElectricUtils, - ErrorUtils, - FileUtils, MessageChannelUtils, Utils, buildChargingStationAutomaticTransactionGeneratorConfiguration, buildConnectorsStatus, buildEvsesStatus, + handleFileException, logger, + watchJsonFile, } from '../utils'; export class ChargingStation { @@ -645,7 +645,7 @@ export class ChargingStation { } this.openWSConnection(); // Monitor charging station template file - this.templateFileWatcher = FileUtils.watchJsonFile( + this.templateFileWatcher = watchJsonFile( this.templateFile, FileType.ChargingStationTemplate, this.logPrefix(), @@ -957,7 +957,7 @@ export class ChargingStation { this.templateFileHash = template.templateHash; } } catch (error) { - ErrorUtils.handleFileException( + handleFileException( this.templateFile, FileType.ChargingStationTemplate, error as NodeJS.ErrnoException, @@ -1539,7 +1539,7 @@ export class ChargingStation { this.configurationFileHash = configuration.configurationHash; } } catch (error) { - ErrorUtils.handleFileException( + handleFileException( this.configurationFile, FileType.ChargingStationConfiguration, error as NodeJS.ErrnoException, @@ -1628,7 +1628,7 @@ export class ChargingStation { this.configurationFileHash = configurationHash; }) .catch((error) => { - ErrorUtils.handleFileException( + handleFileException( this.configurationFile, FileType.ChargingStationConfiguration, error as NodeJS.ErrnoException, @@ -1646,7 +1646,7 @@ export class ChargingStation { ); } } catch (error) { - ErrorUtils.handleFileException( + handleFileException( this.configurationFile, FileType.ChargingStationConfiguration, error as NodeJS.ErrnoException, diff --git a/src/charging-station/IdTagsCache.ts b/src/charging-station/IdTagsCache.ts index fd35fa8b..890ac1fb 100644 --- a/src/charging-station/IdTagsCache.ts +++ b/src/charging-station/IdTagsCache.ts @@ -3,7 +3,7 @@ import fs from 'node:fs'; import type { ChargingStation } from './ChargingStation'; import { ChargingStationUtils } from './ChargingStationUtils'; import { FileType, IdTagDistribution } from '../types'; -import { ErrorUtils, FileUtils, Utils, logger } from '../utils'; +import { Utils, handleFileException, logger, watchJsonFile } from '../utils'; type IdTagsCacheValueType = { idTags: string[]; @@ -116,7 +116,7 @@ export class IdTagsCache { private setIdTagsCache(file: string, idTags: string[]) { return this.idTagsCaches.set(file, { idTags, - idTagsFileWatcher: FileUtils.watchJsonFile( + idTagsFileWatcher: watchJsonFile( file, FileType.Authorization, this.logPrefix(file), @@ -130,7 +130,7 @@ export class IdTagsCache { this.deleteIdTagsCache(file); this.deleteIdTagsCacheIndexes(file); } catch (error) { - ErrorUtils.handleFileException( + handleFileException( file, FileType.Authorization, error as NodeJS.ErrnoException, @@ -172,7 +172,7 @@ export class IdTagsCache { try { return JSON.parse(fs.readFileSync(file, 'utf8')) as string[]; } catch (error) { - ErrorUtils.handleFileException( + handleFileException( file, FileType.Authorization, error as NodeJS.ErrnoException, diff --git a/src/charging-station/ocpp/OCPPIncomingRequestService.ts b/src/charging-station/ocpp/OCPPIncomingRequestService.ts index 4d2b29e3..2a304c31 100644 --- a/src/charging-station/ocpp/OCPPIncomingRequestService.ts +++ b/src/charging-station/ocpp/OCPPIncomingRequestService.ts @@ -15,7 +15,7 @@ import type { JsonType, OCPPVersion, } from '../../types'; -import { ErrorUtils, logger } from '../../utils'; +import { logger, setDefaultErrorParams } from '../../utils'; const moduleName = 'OCPPIncomingRequestService'; @@ -62,7 +62,7 @@ export abstract class OCPPIncomingRequestService extends AsyncResource { error: Error, params: HandleErrorParams = { throwError: true, consoleOut: false } ): T | undefined { - ErrorUtils.setDefaultErrorParams(params); + setDefaultErrorParams(params); logger.error( `${chargingStation.logPrefix()} ${moduleName}.handleIncomingRequestError: Incoming request command '${commandName}' error:`, error diff --git a/src/charging-station/ocpp/OCPPRequestService.ts b/src/charging-station/ocpp/OCPPRequestService.ts index 2a6a8c18..a3b78ca6 100644 --- a/src/charging-station/ocpp/OCPPRequestService.ts +++ b/src/charging-station/ocpp/OCPPRequestService.ts @@ -23,7 +23,7 @@ import { type ResponseCallback, type ResponseType, } from '../../types'; -import { Constants, ErrorUtils, Utils, logger } from '../../utils'; +import { Constants, Utils, handleSendMessageError, logger } from '../../utils'; const moduleName = 'OCPPRequestService'; @@ -133,7 +133,7 @@ export abstract class OCPPRequestService { commandName ); } catch (error) { - ErrorUtils.handleSendMessageError(chargingStation, commandName, error as Error, { + handleSendMessageError(chargingStation, commandName, error as Error, { throwError: true, }); } @@ -155,7 +155,7 @@ export abstract class OCPPRequestService { commandName ); } catch (error) { - ErrorUtils.handleSendMessageError(chargingStation, commandName, error as Error); + handleSendMessageError(chargingStation, commandName, error as Error); } } @@ -180,7 +180,7 @@ export abstract class OCPPRequestService { params ); } catch (error) { - ErrorUtils.handleSendMessageError(chargingStation, commandName, error as Error, { + handleSendMessageError(chargingStation, commandName, error as Error, { throwError: params.throwError, }); } diff --git a/src/charging-station/ocpp/OCPPServiceUtils.ts b/src/charging-station/ocpp/OCPPServiceUtils.ts index a4702dd6..078fa0a0 100644 --- a/src/charging-station/ocpp/OCPPServiceUtils.ts +++ b/src/charging-station/ocpp/OCPPServiceUtils.ts @@ -30,7 +30,7 @@ import { type StatusNotificationRequest, type StatusNotificationResponse, } from '../../types'; -import { ErrorUtils, Utils, logger } from '../../utils'; +import { Utils, handleFileException, logger } from '../../utils'; export class OCPPServiceUtils { protected constructor() { @@ -264,7 +264,7 @@ export class OCPPServiceUtils { try { return JSON.parse(fs.readFileSync(filePath, 'utf8')) as JSONSchemaType; } catch (error) { - ErrorUtils.handleFileException( + handleFileException( filePath, FileType.JsonSchema, error as NodeJS.ErrnoException, diff --git a/src/performance/storage/JsonFileStorage.ts b/src/performance/storage/JsonFileStorage.ts index 2a712a60..0fd29d02 100644 --- a/src/performance/storage/JsonFileStorage.ts +++ b/src/performance/storage/JsonFileStorage.ts @@ -6,7 +6,7 @@ import path from 'node:path'; import { Storage } from './Storage'; import { BaseError } from '../../exception'; import { FileType, type Statistics } from '../../types'; -import { AsyncLock, AsyncLockType, Constants, ErrorUtils, Utils } from '../../utils'; +import { AsyncLock, AsyncLockType, Constants, Utils, handleFileException } from '../../utils'; export class JsonFileStorage extends Storage { private fd: number | null = null; @@ -32,7 +32,7 @@ export class JsonFileStorage extends Storage { ); }) .catch((error) => { - ErrorUtils.handleFileException( + handleFileException( this.dbName, FileType.PerformanceRecords, error as NodeJS.ErrnoException, @@ -53,7 +53,7 @@ export class JsonFileStorage extends Storage { this.fd = fs.openSync(this.dbName, 'a+'); } } catch (error) { - ErrorUtils.handleFileException( + handleFileException( this.dbName, FileType.PerformanceRecords, error as NodeJS.ErrnoException, @@ -69,7 +69,7 @@ export class JsonFileStorage extends Storage { this.fd = null; } } catch (error) { - ErrorUtils.handleFileException( + handleFileException( this.dbName, FileType.PerformanceRecords, error as NodeJS.ErrnoException, diff --git a/src/performance/storage/Storage.ts b/src/performance/storage/Storage.ts index 39345cdf..1360dabb 100644 --- a/src/performance/storage/Storage.ts +++ b/src/performance/storage/Storage.ts @@ -9,7 +9,7 @@ import { type Statistics, StorageType, } from '../../types'; -import { ErrorUtils, Utils, logger } from '../../utils'; +import { Utils, logger, setDefaultErrorParams } from '../../utils'; export abstract class Storage { protected readonly storageUri: URL; @@ -27,7 +27,7 @@ export abstract class Storage { table?: string, params: HandleErrorParams = { throwError: false, consoleOut: false } ): void { - ErrorUtils.setDefaultErrorParams(params, { throwError: false, consoleOut: false }); + setDefaultErrorParams(params, { throwError: false, consoleOut: false }); const inTableOrCollectionStr = (!Utils.isNullOrUndefined(table) || !table) && ` in table or collection '${table}'`; logger.error( diff --git a/src/utils/ErrorUtils.ts b/src/utils/ErrorUtils.ts index bca12b64..b4f52ba8 100644 --- a/src/utils/ErrorUtils.ts +++ b/src/utils/ErrorUtils.ts @@ -17,85 +17,79 @@ const defaultErrorParams = { consoleOut: false, }; -export class ErrorUtils { - private constructor() { - // This is intentional - } +export const handleUncaughtException = (): void => { + process.on('uncaughtException', (error: Error) => { + console.error(chalk.red('Uncaught exception: '), error); + }); +}; - public static handleUncaughtException(): void { - process.on('uncaughtException', (error: Error) => { - console.error(chalk.red('Uncaught exception: '), error); - }); - } +export const handleUnhandledRejection = (): void => { + process.on('unhandledRejection', (reason: unknown) => { + console.error(chalk.red('Unhandled rejection: '), reason); + }); +}; - public static handleUnhandledRejection(): void { - process.on('unhandledRejection', (reason: unknown) => { - console.error(chalk.red('Unhandled rejection: '), reason); - }); +export const handleFileException = ( + file: string, + fileType: FileType, + error: NodeJS.ErrnoException, + logPrefix: string, + params: HandleErrorParams = defaultErrorParams +): void => { + setDefaultErrorParams(params); + const prefix = Utils.isNotEmptyString(logPrefix) ? `${logPrefix} ` : ''; + let logMsg: string; + switch (error.code) { + case 'ENOENT': + logMsg = `${fileType} file ${file} not found:`; + break; + case 'EEXIST': + logMsg = `${fileType} file ${file} already exists:`; + break; + case 'EACCES': + logMsg = `${fileType} file ${file} access denied:`; + break; + case 'EPERM': + logMsg = `${fileType} file ${file} permission denied:`; + break; + default: + logMsg = `${fileType} file ${file} error:`; } - - public static handleFileException( - file: string, - fileType: FileType, - error: NodeJS.ErrnoException, - logPrefix: string, - params: HandleErrorParams = defaultErrorParams - ): void { - ErrorUtils.setDefaultErrorParams(params); - const prefix = Utils.isNotEmptyString(logPrefix) ? `${logPrefix} ` : ''; - let logMsg: string; - switch (error.code) { - case 'ENOENT': - logMsg = `${fileType} file ${file} not found:`; - break; - case 'EEXIST': - logMsg = `${fileType} file ${file} already exists:`; - break; - case 'EACCES': - logMsg = `${fileType} file ${file} access denied:`; - break; - case 'EPERM': - logMsg = `${fileType} file ${file} permission denied:`; - break; - default: - logMsg = `${fileType} file ${file} error:`; - } - if (params?.consoleOut === true) { - if (params?.throwError) { - console.error(`${chalk.green(prefix)}${chalk.red(`${logMsg} `)}`, error); - } else { - console.warn(`${chalk.green(prefix)}${chalk.yellow(`${logMsg} `)}`, error); - } - } else if (params?.consoleOut === false) { - if (params?.throwError) { - logger.error(`${prefix}${logMsg}`, error); - } else { - logger.warn(`${prefix}${logMsg}`, error); - } + if (params?.consoleOut === true) { + if (params?.throwError) { + console.error(`${chalk.green(prefix)}${chalk.red(`${logMsg} `)}`, error); + } else { + console.warn(`${chalk.green(prefix)}${chalk.yellow(`${logMsg} `)}`, error); } + } else if (params?.consoleOut === false) { if (params?.throwError) { - throw error; + logger.error(`${prefix}${logMsg}`, error); + } else { + logger.warn(`${prefix}${logMsg}`, error); } } - - public static handleSendMessageError( - chargingStation: ChargingStation, - commandName: RequestCommand | IncomingRequestCommand, - error: Error, - params: HandleErrorParams = { throwError: false, consoleOut: false } - ): void { - ErrorUtils.setDefaultErrorParams(params, { throwError: false, consoleOut: false }); - logger.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error); - if (params?.throwError === true) { - throw error; - } + if (params?.throwError) { + throw error; } +}; - public static setDefaultErrorParams( - params: HandleErrorParams, - defaultParams: HandleErrorParams = defaultErrorParams - ): HandleErrorParams { - params = { ...defaultParams, ...params }; - return params; +export const handleSendMessageError = ( + chargingStation: ChargingStation, + commandName: RequestCommand | IncomingRequestCommand, + error: Error, + params: HandleErrorParams = { throwError: false, consoleOut: false } +): void => { + setDefaultErrorParams(params, { throwError: false, consoleOut: false }); + logger.error(`${chargingStation.logPrefix()} Request command '${commandName}' error:`, error); + if (params?.throwError === true) { + throw error; } -} +}; + +export const setDefaultErrorParams = ( + params: HandleErrorParams, + defaultParams: HandleErrorParams = defaultErrorParams +): HandleErrorParams => { + params = { ...defaultParams, ...params }; + return params; +}; diff --git a/src/utils/FileUtils.ts b/src/utils/FileUtils.ts index 4e556a4b..51871884 100644 --- a/src/utils/FileUtils.ts +++ b/src/utils/FileUtils.ts @@ -1,49 +1,37 @@ import fs from 'node:fs'; -import { ErrorUtils } from './ErrorUtils'; +import { handleFileException } from './ErrorUtils'; import { logger } from './Logger'; import { Utils } from './Utils'; import type { FileType, JsonType } from '../types'; -export class FileUtils { - private constructor() { - // This is intentional - } - - public static watchJsonFile( - file: string, - fileType: FileType, - logPrefix: string, - refreshedVariable?: T, - listener: fs.WatchListener = (event, filename) => { - if (Utils.isNotEmptyString(filename) && event === 'change') { - try { - logger.debug(`${logPrefix} ${fileType} file ${file} have changed, reload`); - refreshedVariable && (refreshedVariable = JSON.parse(fs.readFileSync(file, 'utf8')) as T); - } catch (error) { - ErrorUtils.handleFileException( - file, - fileType, - error as NodeJS.ErrnoException, - logPrefix, - { - throwError: false, - } - ); - } - } - } - ): fs.FSWatcher | undefined { - if (Utils.isNotEmptyString(file)) { +export const watchJsonFile = ( + file: string, + fileType: FileType, + logPrefix: string, + refreshedVariable?: T, + listener: fs.WatchListener = (event, filename) => { + if (Utils.isNotEmptyString(filename) && event === 'change') { try { - return fs.watch(file, listener); + logger.debug(`${logPrefix} ${fileType} file ${file} have changed, reload`); + refreshedVariable && (refreshedVariable = JSON.parse(fs.readFileSync(file, 'utf8')) as T); } catch (error) { - ErrorUtils.handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, { + handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, { throwError: false, }); } - } else { - logger.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`); } } -} +): fs.FSWatcher | undefined => { + if (Utils.isNotEmptyString(file)) { + try { + return fs.watch(file, listener); + } catch (error) { + handleFileException(file, fileType, error as NodeJS.ErrnoException, logPrefix, { + throwError: false, + }); + } + } else { + logger.info(`${logPrefix} No ${fileType} file to watch given. Not monitoring its changes`); + } +}; diff --git a/src/utils/index.ts b/src/utils/index.ts index b034c9a2..2273562e 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -9,8 +9,14 @@ export { export { CircularArray } from './CircularArray'; export { Configuration } from './Configuration'; export { Constants } from './Constants'; -export { ErrorUtils } from './ErrorUtils'; -export { FileUtils } from './FileUtils'; +export { + handleFileException, + handleUncaughtException, + handleUnhandledRejection, + handleSendMessageError, + setDefaultErrorParams, +} from './ErrorUtils'; +export { watchJsonFile } from './FileUtils'; export { MessageChannelUtils } from './MessageChannelUtils'; export { Utils } from './Utils'; export { logger } from './Logger';