From 1895299db899eb53db7fb1615b82624f806017e8 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Wed, 25 Jan 2023 14:47:06 +0100 Subject: [PATCH] Strict null type check fixes MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- src/charging-station/AuthorizedTagsCache.ts | 10 +- .../AutomaticTransactionGenerator.ts | 12 +- src/charging-station/Bootstrap.ts | 14 +- src/charging-station/ChargingStation.ts | 33 +++-- .../ChargingStationConfigurationUtils.ts | 6 +- src/charging-station/ChargingStationUtils.ts | 8 +- src/charging-station/SharedLRUCache.ts | 2 +- src/performance/PerformanceStatistics.ts | 6 +- src/performance/storage/MikroOrmStorage.ts | 6 +- src/performance/storage/Storage.ts | 4 +- src/performance/storage/StorageFactory.ts | 2 +- src/types/ChargingStationWorker.ts | 2 +- src/types/Worker.ts | 4 +- src/utils/Configuration.ts | 134 ++++++++++-------- src/utils/FileUtils.ts | 2 +- src/utils/Logger.ts | 4 +- src/utils/Utils.ts | 4 +- src/worker/WorkerFactory.ts | 2 +- 18 files changed, 133 insertions(+), 122 deletions(-) diff --git a/src/charging-station/AuthorizedTagsCache.ts b/src/charging-station/AuthorizedTagsCache.ts index 4f853a97..5808f02b 100644 --- a/src/charging-station/AuthorizedTagsCache.ts +++ b/src/charging-station/AuthorizedTagsCache.ts @@ -8,11 +8,11 @@ import Utils from '../utils/Utils'; export default class AuthorizedTagsCache { private static instance: AuthorizedTagsCache | null = null; private readonly tagsCaches: Map; - private readonly FSWatchers: Map; + private readonly FSWatchers: Map; private constructor() { this.tagsCaches = new Map(); - this.FSWatchers = new Map(); + this.FSWatchers = new Map(); } public static getInstance(): AuthorizedTagsCache { @@ -22,7 +22,7 @@ export default class AuthorizedTagsCache { return AuthorizedTagsCache.instance; } - public getAuthorizedTags(file: string): string[] { + public getAuthorizedTags(file: string): string[] | undefined { if (this.hasTags(file) === false) { this.setTags(file, this.getAuthorizedTagsFromFile(file)); // Monitor authorization file @@ -73,7 +73,7 @@ export default class AuthorizedTagsCache { return this.tagsCaches.set(file, tags); } - private getTags(file: string): string[] { + private getTags(file: string): string[] | undefined { return this.tagsCaches.get(file); } @@ -82,7 +82,7 @@ export default class AuthorizedTagsCache { } private deleteFSWatcher(file: string): boolean { - this.FSWatchers.get(file).close(); + this.FSWatchers.get(file)?.close(); return this.FSWatchers.delete(file); } diff --git a/src/charging-station/AutomaticTransactionGenerator.ts b/src/charging-station/AutomaticTransactionGenerator.ts index 3a1c6786..2774149e 100644 --- a/src/charging-station/AutomaticTransactionGenerator.ts +++ b/src/charging-station/AutomaticTransactionGenerator.ts @@ -55,7 +55,7 @@ export default class AutomaticTransactionGenerator extends AsyncResource { public static getInstance( automaticTransactionGeneratorConfiguration: AutomaticTransactionGeneratorConfiguration, chargingStation: ChargingStation - ): AutomaticTransactionGenerator { + ): AutomaticTransactionGenerator | undefined { if (AutomaticTransactionGenerator.instances.has(chargingStation.stationInfo.hashId) === false) { AutomaticTransactionGenerator.instances.set( chargingStation.stationInfo.hashId, @@ -158,7 +158,7 @@ export default class AutomaticTransactionGenerator extends AsyncResource { this.connectorsStatus.get(connectorId).startDate.getTime() )}` ); - while (this.connectorsStatus.get(connectorId).start === true) { + while (this.connectorsStatus.get(connectorId)?.start === true) { if (new Date() > this.connectorsStatus.get(connectorId).stopDate) { this.stopConnector(connectorId); break; @@ -231,7 +231,7 @@ export default class AutomaticTransactionGenerator extends AsyncResource { logger.info( `${this.logPrefix(connectorId)} stop transaction ${this.chargingStation .getConnectorStatus(connectorId) - .transactionId.toString()}` + ?.transactionId?.toString()}` ); await this.stopTransaction(connectorId); } @@ -241,9 +241,9 @@ export default class AutomaticTransactionGenerator extends AsyncResource { logger.info( `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus .get(connectorId) - .skippedConsecutiveTransactions.toString()}/${this.connectorsStatus + ?.skippedConsecutiveTransactions?.toString()}/${this.connectorsStatus .get(connectorId) - .skippedTransactions.toString()} transaction(s)` + ?.skippedTransactions?.toString()} transaction(s)` ); } this.connectorsStatus.get(connectorId).lastRunDate = new Date(); @@ -384,7 +384,7 @@ export default class AutomaticTransactionGenerator extends AsyncResource { this.connectorsStatus.get(connectorId).rejectedStopTransactionRequests++; } } else { - const transactionId = this.chargingStation.getConnectorStatus(connectorId).transactionId; + const transactionId = this.chargingStation.getConnectorStatus(connectorId)?.transactionId; logger.warn( `${this.logPrefix(connectorId)} stopping a not started transaction${ transactionId ? ` ${transactionId.toString()}` : '' diff --git a/src/charging-station/Bootstrap.ts b/src/charging-station/Bootstrap.ts index ca45d287..9f910aaf 100644 --- a/src/charging-station/Bootstrap.ts +++ b/src/charging-station/Bootstrap.ts @@ -83,7 +83,7 @@ export class Bootstrap { this.logUncaughtException(); this.initialize(); await this.storage?.open(); - await this.workerImplementation.start(); + await this.workerImplementation?.start(); this.uiServer?.start(); const stationTemplateUrls = Configuration.getStationTemplateUrls(); this.numberOfChargingStationTemplates = stationTemplateUrls.length; @@ -122,15 +122,15 @@ export class Bootstrap { this.version } started with ${this.numberOfChargingStations.toString()} charging station(s) from ${this.numberOfChargingStationTemplates.toString()} configured charging station template(s) and ${ ChargingStationUtils.workerDynamicPoolInUse() - ? `${Configuration.getWorker().poolMinSize.toString()}/` + ? `${Configuration.getWorker().poolMinSize?.toString()}/` : '' - }${this.workerImplementation.size}${ + }${this.workerImplementation?.size}${ ChargingStationUtils.workerPoolInUse() - ? `/${Configuration.getWorker().poolMaxSize.toString()}` + ? `/${Configuration.getWorker().poolMaxSize?.toString()}` : '' } worker(s) concurrently running in '${Configuration.getWorker().processType}' mode${ - this.workerImplementation.maxElementsPerWorker - ? ` (${this.workerImplementation.maxElementsPerWorker} charging station(s) per worker)` + this.workerImplementation?.maxElementsPerWorker + ? ` (${this.workerImplementation?.maxElementsPerWorker} charging station(s) per worker)` : '' }` ) @@ -147,7 +147,7 @@ export class Bootstrap { public async stop(): Promise { if (isMainThread && this.started === true) { - await this.workerImplementation.stop(); + await this.workerImplementation?.stop(); this.workerImplementation = null; this.uiServer?.stop(); await this.storage?.close(); diff --git a/src/charging-station/ChargingStation.ts b/src/charging-station/ChargingStation.ts index acee101d..4a90c310 100644 --- a/src/charging-station/ChargingStation.ts +++ b/src/charging-station/ChargingStation.ts @@ -109,7 +109,7 @@ export default class ChargingStation { public heartbeatSetInterval!: NodeJS.Timeout; public ocppRequestService!: OCPPRequestService; public bootNotificationRequest!: BootNotificationRequest; - public bootNotificationResponse!: BootNotificationResponse | null; + public bootNotificationResponse!: BootNotificationResponse | undefined; public powerDivider!: number; private stopping: boolean; private configurationFile!: string; @@ -202,7 +202,7 @@ export default class ChargingStation { return this?.wsConnection?.readyState === WebSocket.OPEN; } - public getRegistrationStatus(): RegistrationStatusEnumType { + public getRegistrationStatus(): RegistrationStatusEnumType | undefined { return this?.bootNotificationResponse?.status; } @@ -230,11 +230,11 @@ export default class ChargingStation { } public isChargingStationAvailable(): boolean { - return this.getConnectorStatus(0).availability === AvailabilityType.OPERATIVE; + return this.getConnectorStatus(0)?.availability === AvailabilityType.OPERATIVE; } public isConnectorAvailable(id: number): boolean { - return id > 0 && this.getConnectorStatus(id).availability === AvailabilityType.OPERATIVE; + return id > 0 && this.getConnectorStatus(id)?.availability === AvailabilityType.OPERATIVE; } public getNumberOfConnectors(): number { @@ -300,7 +300,10 @@ export default class ChargingStation { public getTransactionIdTag(transactionId: number): string | undefined { for (const connectorId of this.connectors.keys()) { - if (connectorId > 0 && this.getConnectorStatus(connectorId).transactionId === transactionId) { + if ( + connectorId > 0 && + this.getConnectorStatus(connectorId)?.transactionId === transactionId + ) { return this.getConnectorStatus(connectorId).transactionIdTag; } } @@ -541,7 +544,7 @@ export default class ChargingStation { } ); this.started = true; - parentPort.postMessage(MessageChannelUtils.buildStartedMessage(this)); + parentPort?.postMessage(MessageChannelUtils.buildStartedMessage(this)); this.starting = false; } else { logger.warn(`${this.logPrefix()} Charging station is already starting...`); @@ -563,9 +566,9 @@ export default class ChargingStation { this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash); this.templateFileWatcher.close(); this.sharedLRUCache.deleteChargingStationTemplate(this.stationInfo?.templateHash); - this.bootNotificationResponse = null; + this.bootNotificationResponse = undefined; this.started = false; - parentPort.postMessage(MessageChannelUtils.buildStoppedMessage(this)); + parentPort?.postMessage(MessageChannelUtils.buildStoppedMessage(this)); this.stopping = false; } else { logger.warn(`${this.logPrefix()} Charging station is already stopping...`); @@ -600,7 +603,7 @@ export default class ChargingStation { this.getConnectorStatus(connectorId).transactionEnergyActiveImportRegisterValue = 0; delete this.getConnectorStatus(connectorId).transactionBeginMeterValue; this.stopMeterValues(connectorId); - parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); + parentPort?.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); } public hasFeatureProfile(featureProfile: SupportedFeatureProfiles): boolean { @@ -714,7 +717,7 @@ export default class ChargingStation { } else { this.automaticTransactionGenerator.start(); } - parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); + parentPort?.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); } public stopAutomaticTransactionGenerator(connectorIds?: number[]): void { @@ -725,7 +728,7 @@ export default class ChargingStation { } else { this.automaticTransactionGenerator?.stop(); } - parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); + parentPort?.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); } public async stopTransactionOnConnector( @@ -1431,7 +1434,7 @@ export default class ChargingStation { if (this.isRegistered() === false) { this.getRegistrationMaxRetries() !== -1 && registrationRetryCount++; await Utils.sleep( - this.bootNotificationResponse?.interval + this?.bootNotificationResponse?.interval ? this.bootNotificationResponse.interval * 1000 : Constants.OCPP_DEFAULT_BOOT_NOTIFICATION_INTERVAL ); @@ -1453,7 +1456,7 @@ export default class ChargingStation { } this.wsConnectionRestarted = false; this.autoReconnectRetryCount = 0; - parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); + parentPort?.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); } else { logger.warn( `${this.logPrefix()} Connection to OCPP server through ${this.wsConnectionUrl.toString()} failed` @@ -1483,7 +1486,7 @@ export default class ChargingStation { this.started === true && (await this.reconnect()); break; } - parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); + parentPort?.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); } private async onMessage(data: RawData): Promise { @@ -1593,7 +1596,7 @@ export default class ChargingStation { logger.error(`${this.logPrefix()} ${errMsg}`); throw new OCPPError(ErrorType.PROTOCOL_ERROR, errMsg); } - parentPort.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); + parentPort?.postMessage(MessageChannelUtils.buildUpdatedMessage(this)); } else { throw new OCPPError(ErrorType.PROTOCOL_ERROR, 'Incoming message is not an array', null, { request, diff --git a/src/charging-station/ChargingStationConfigurationUtils.ts b/src/charging-station/ChargingStationConfigurationUtils.ts index 4e0d55cc..4bae70f2 100644 --- a/src/charging-station/ChargingStationConfigurationUtils.ts +++ b/src/charging-station/ChargingStationConfigurationUtils.ts @@ -17,7 +17,7 @@ export class ChargingStationConfigurationUtils { key: string | StandardParametersKey, caseInsensitive = false ): ConfigurationKey | undefined { - return chargingStation.ocppConfiguration.configurationKey.find(configElement => { + return chargingStation.ocppConfiguration.configurationKey?.find(configElement => { if (caseInsensitive) { return configElement.key.toLowerCase() === key.toLowerCase(); } @@ -48,7 +48,7 @@ export class ChargingStationConfigurationUtils { keyFound = undefined; } if (!keyFound) { - chargingStation.ocppConfiguration.configurationKey.push({ + chargingStation.ocppConfiguration.configurationKey?.push({ key, readonly: options.readonly, value, @@ -92,7 +92,7 @@ export class ChargingStationConfigurationUtils { chargingStation: ChargingStation, key: string | StandardParametersKey, params: DeleteConfigurationKeyParams = { save: true, caseInsensitive: false } - ): ConfigurationKey[] { + ): ConfigurationKey[] | undefined { const keyFound = ChargingStationConfigurationUtils.getConfigurationKey( chargingStation, key, diff --git a/src/charging-station/ChargingStationUtils.ts b/src/charging-station/ChargingStationUtils.ts index 426ff5c0..44b7dee0 100644 --- a/src/charging-station/ChargingStationUtils.ts +++ b/src/charging-station/ChargingStationUtils.ts @@ -325,9 +325,9 @@ export class ChargingStationUtils { // Get charging profiles for connector and sort by stack level chargingProfiles = chargingStation .getConnectorStatus(connectorId) - .chargingProfiles.sort((a, b) => b.stackLevel - a.stackLevel); + ?.chargingProfiles?.sort((a, b) => b.stackLevel - a.stackLevel); // Get profiles on connector 0 - if (chargingStation.getConnectorStatus(0).chargingProfiles) { + if (chargingStation.getConnectorStatus(0)?.chargingProfiles) { chargingProfiles.push( ...chargingStation .getConnectorStatus(0) @@ -340,8 +340,8 @@ export class ChargingStationUtils { chargingStation.logPrefix() ); if (!Utils.isNullOrUndefined(result)) { - limit = result.limit; - matchingChargingProfile = result.matchingChargingProfile; + limit = result?.limit; + matchingChargingProfile = result?.matchingChargingProfile; switch (chargingStation.getCurrentOutType()) { case CurrentType.AC: limit = diff --git a/src/charging-station/SharedLRUCache.ts b/src/charging-station/SharedLRUCache.ts index 14817511..e235c51d 100644 --- a/src/charging-station/SharedLRUCache.ts +++ b/src/charging-station/SharedLRUCache.ts @@ -90,7 +90,7 @@ export default class SharedLRUCache { return this.lruCache.has(key); } - private get(key: string): CacheableType { + private get(key: string): CacheableType | undefined { return this.lruCache.get(key); } diff --git a/src/performance/PerformanceStatistics.ts b/src/performance/PerformanceStatistics.ts index 6c0ff042..6d18e212 100644 --- a/src/performance/PerformanceStatistics.ts +++ b/src/performance/PerformanceStatistics.ts @@ -21,9 +21,9 @@ export default class PerformanceStatistics { private readonly objId: string; private readonly objName: string; - private performanceObserver: PerformanceObserver; + private performanceObserver!: PerformanceObserver; private readonly statistics: Statistics; - private displayInterval: NodeJS.Timeout; + private displayInterval!: NodeJS.Timeout; private constructor(objId: string, objName: string, uri: URL) { this.objId = objId; @@ -280,7 +280,7 @@ export default class PerformanceStatistics { ) ); if (Configuration.getPerformanceStorage().enabled) { - parentPort.postMessage( + parentPort?.postMessage( MessageChannelUtils.buildPerformanceStatisticsMessage(this.statistics) ); } diff --git a/src/performance/storage/MikroOrmStorage.ts b/src/performance/storage/MikroOrmStorage.ts index 70a89030..69905d8d 100644 --- a/src/performance/storage/MikroOrmStorage.ts +++ b/src/performance/storage/MikroOrmStorage.ts @@ -12,7 +12,7 @@ import Constants from '../../utils/Constants'; export class MikroOrmStorage extends Storage { private storageType: StorageType; - private orm: MikroORM | null; + private orm!: MikroORM | null; constructor(storageUri: string, logPrefix: string, storageType: StorageType) { super(storageUri, logPrefix); @@ -23,7 +23,7 @@ export class MikroOrmStorage extends Storage { public async storePerformanceStatistics(performanceStatistics: Statistics): Promise { try { const performanceRecord = new PerformanceRecord(); - await this.orm.em.persistAndFlush(performanceRecord); + await this.orm?.em.persistAndFlush(performanceRecord); } catch (error) { this.handleDBError(this.storageType, error as Error, Constants.PERFORMANCE_RECORDS_TABLE); } @@ -71,7 +71,7 @@ export class MikroOrmStorage extends Storage { }; } - private getClientUrl(): string { + private getClientUrl(): string | undefined { switch (this.storageType) { case StorageType.SQLITE: case StorageType.MARIA_DB: diff --git a/src/performance/storage/Storage.ts b/src/performance/storage/Storage.ts index 9c4696fa..5fb0fb61 100644 --- a/src/performance/storage/Storage.ts +++ b/src/performance/storage/Storage.ts @@ -12,7 +12,7 @@ import Utils from '../../utils/Utils'; export abstract class Storage { protected readonly storageUri: URL; protected readonly logPrefix: string; - protected dbName: string; + protected dbName!: string; constructor(storageUri: string, logPrefix: string) { this.storageUri = new URL(storageUri); @@ -38,7 +38,7 @@ export abstract class Storage { } } - protected getDBNameFromStorageType(type: StorageType): DBName { + protected getDBNameFromStorageType(type: StorageType): DBName | undefined { switch (type) { case StorageType.MARIA_DB: return DBName.MARIA_DB; diff --git a/src/performance/storage/StorageFactory.ts b/src/performance/storage/StorageFactory.ts index 2007e8f4..3da99725 100644 --- a/src/performance/storage/StorageFactory.ts +++ b/src/performance/storage/StorageFactory.ts @@ -12,7 +12,7 @@ export class StorageFactory { } public static getStorage(type: StorageType, connectionUri: string, logPrefix: string): Storage { - let storageInstance: Storage = null; + let storageInstance: Storage | null = null; switch (type) { case StorageType.JSON_FILE: storageInstance = new JsonFileStorage(connectionUri, logPrefix); diff --git a/src/types/ChargingStationWorker.ts b/src/types/ChargingStationWorker.ts index c27ec6eb..f0a58013 100644 --- a/src/types/ChargingStationWorker.ts +++ b/src/types/ChargingStationWorker.ts @@ -26,7 +26,7 @@ export interface ChargingStationData extends WorkerData { | typeof WebSocket.OPEN | typeof WebSocket.CLOSING | typeof WebSocket.CLOSED; - bootNotificationResponse: BootNotificationResponse; + bootNotificationResponse?: BootNotificationResponse; connectors: ConnectorStatus[]; automaticTransactionGenerator?: ChargingStationAutomaticTransactionGeneratorConfiguration; } diff --git a/src/types/Worker.ts b/src/types/Worker.ts index 12c2ea36..9204eadc 100644 --- a/src/types/Worker.ts +++ b/src/types/Worker.ts @@ -13,8 +13,8 @@ export type MessageHandler = (this: T, message: unknown) => void; export type WorkerOptions = { workerStartDelay?: number; elementStartDelay?: number; - poolMaxSize?: number; - poolMinSize?: number; + poolMaxSize: number; + poolMinSize: number; elementsPerWorker?: number; poolOptions?: PoolOptions; messageHandler?: MessageHandler; diff --git a/src/utils/Configuration.ts b/src/utils/Configuration.ts index 03789f15..a67c70c2 100644 --- a/src/utils/Configuration.ts +++ b/src/utils/Configuration.ts @@ -30,7 +30,7 @@ export default class Configuration { 'config.json' ); - private static configurationFileWatcher: fs.FSWatcher; + private static configurationFileWatcher: fs.FSWatcher | undefined; private static configuration: ConfigurationData | null = null; private static configurationChangeCallback: () => Promise; @@ -42,15 +42,15 @@ export default class Configuration { Configuration.configurationChangeCallback = cb; } - static getLogStatisticsInterval(): number { + static getLogStatisticsInterval(): number | undefined { Configuration.warnDeprecatedConfigurationKey( 'statisticsDisplayInterval', - null, + undefined, "Use 'logStatisticsInterval' instead" ); // Read conf return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logStatisticsInterval') - ? Configuration.getConfig().logStatisticsInterval + ? Configuration.getConfig()?.logStatisticsInterval : Constants.DEFAULT_LOG_STATISTICS_INTERVAL; } @@ -69,7 +69,7 @@ export default class Configuration { }, }; if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'uiServer')) { - uiServerConfiguration = merge(uiServerConfiguration, Configuration.getConfig().uiServer); + uiServerConfiguration = merge(uiServerConfiguration, Configuration.getConfig()?.uiServer); } if (Configuration.isCFEnvironment() === true) { delete uiServerConfiguration.options.host; @@ -88,44 +88,44 @@ export default class Configuration { if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'performanceStorage')) { storageConfiguration = { ...storageConfiguration, - ...Configuration.getConfig().performanceStorage, + ...Configuration.getConfig()?.performanceStorage, }; } return storageConfiguration; } - static getAutoReconnectMaxRetries(): number { + static getAutoReconnectMaxRetries(): number | undefined { Configuration.warnDeprecatedConfigurationKey( 'autoReconnectTimeout', - null, + undefined, "Use 'ConnectionTimeOut' OCPP parameter in charging station template instead" ); Configuration.warnDeprecatedConfigurationKey( 'connectionTimeout', - null, + undefined, "Use 'ConnectionTimeOut' OCPP parameter in charging station template instead" ); Configuration.warnDeprecatedConfigurationKey( 'autoReconnectMaxRetries', - null, + undefined, 'Use it in charging station template instead' ); // Read conf if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'autoReconnectMaxRetries')) { - return Configuration.getConfig().autoReconnectMaxRetries; + return Configuration.getConfig()?.autoReconnectMaxRetries; } } - static getStationTemplateUrls(): StationTemplateUrl[] { + static getStationTemplateUrls(): StationTemplateUrl[] | undefined { Configuration.warnDeprecatedConfigurationKey( 'stationTemplateURLs', - null, + undefined, "Use 'stationTemplateUrls' instead" ); !Configuration.isUndefined(Configuration.getConfig()['stationTemplateURLs']) && (Configuration.getConfig().stationTemplateUrls = Configuration.getConfig()[ 'stationTemplateURLs' - ] as StationTemplateUrl[]); + ] as unknown as StationTemplateUrl[]); Configuration.getConfig().stationTemplateUrls.forEach((stationUrl: StationTemplateUrl) => { if (!Configuration.isUndefined(stationUrl['numberOfStation'])) { console.error( @@ -136,177 +136,185 @@ export default class Configuration { } }); // Read conf - return Configuration.getConfig().stationTemplateUrls; + return Configuration.getConfig()?.stationTemplateUrls; } static getWorker(): WorkerConfiguration { Configuration.warnDeprecatedConfigurationKey( 'useWorkerPool', - null, + undefined, "Use 'worker' section to define the type of worker process model instead" ); Configuration.warnDeprecatedConfigurationKey( 'workerProcess', - null, + undefined, "Use 'worker' section to define the type of worker process model instead" ); Configuration.warnDeprecatedConfigurationKey( 'workerStartDelay', - null, + undefined, "Use 'worker' section to define the worker start delay instead" ); Configuration.warnDeprecatedConfigurationKey( 'chargingStationsPerWorker', - null, + undefined, "Use 'worker' section to define the number of element(s) per worker instead" ); Configuration.warnDeprecatedConfigurationKey( 'elementStartDelay', - null, + undefined, "Use 'worker' section to define the worker's element start delay instead" ); Configuration.warnDeprecatedConfigurationKey( 'workerPoolMinSize', - null, + undefined, "Use 'worker' section to define the worker pool minimum size instead" ); Configuration.warnDeprecatedConfigurationKey( 'workerPoolSize;', - null, + undefined, "Use 'worker' section to define the worker pool maximum size instead" ); Configuration.warnDeprecatedConfigurationKey( 'workerPoolMaxSize;', - null, + undefined, "Use 'worker' section to define the worker pool maximum size instead" ); Configuration.warnDeprecatedConfigurationKey( 'workerPoolStrategy;', - null, + undefined, "Use 'worker' section to define the worker pool strategy instead" ); let workerConfiguration: WorkerConfiguration = { processType: Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerProcess') - ? Configuration.getConfig().workerProcess + ? Configuration.getConfig()?.workerProcess : WorkerProcessType.WORKER_SET, startDelay: Configuration.objectHasOwnProperty(Configuration.getConfig(), 'workerStartDelay') - ? Configuration.getConfig().workerStartDelay + ? Configuration.getConfig()?.workerStartDelay : WorkerConstants.DEFAULT_WORKER_START_DELAY, elementsPerWorker: Configuration.objectHasOwnProperty( Configuration.getConfig(), 'chargingStationsPerWorker' ) - ? Configuration.getConfig().chargingStationsPerWorker + ? Configuration.getConfig()?.chargingStationsPerWorker : WorkerConstants.DEFAULT_ELEMENTS_PER_WORKER, elementStartDelay: Configuration.objectHasOwnProperty( Configuration.getConfig(), 'elementStartDelay' ) - ? Configuration.getConfig().elementStartDelay + ? Configuration.getConfig()?.elementStartDelay : WorkerConstants.DEFAULT_ELEMENT_START_DELAY, poolMinSize: Configuration.objectHasOwnProperty( Configuration.getConfig(), 'workerPoolMinSize' ) - ? Configuration.getConfig().workerPoolMinSize + ? Configuration.getConfig()?.workerPoolMinSize : WorkerConstants.DEFAULT_POOL_MIN_SIZE, poolMaxSize: Configuration.objectHasOwnProperty( Configuration.getConfig(), 'workerPoolMaxSize' ) - ? Configuration.getConfig().workerPoolMaxSize + ? Configuration.getConfig()?.workerPoolMaxSize : WorkerConstants.DEFAULT_POOL_MAX_SIZE, poolStrategy: - Configuration.getConfig().workerPoolStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN, + Configuration.getConfig()?.workerPoolStrategy ?? WorkerChoiceStrategies.ROUND_ROBIN, }; if (Configuration.objectHasOwnProperty(Configuration.getConfig(), 'worker')) { - workerConfiguration = { ...workerConfiguration, ...Configuration.getConfig().worker }; + workerConfiguration = { ...workerConfiguration, ...Configuration.getConfig()?.worker }; } return workerConfiguration; } - static getLogConsole(): boolean { - Configuration.warnDeprecatedConfigurationKey('consoleLog', null, "Use 'logConsole' instead"); + static getLogConsole(): boolean | undefined { + Configuration.warnDeprecatedConfigurationKey( + 'consoleLog', + undefined, + "Use 'logConsole' instead" + ); return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logConsole') - ? Configuration.getConfig().logConsole + ? Configuration.getConfig()?.logConsole : false; } - static getLogFormat(): string { + static getLogFormat(): string | undefined { return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFormat') - ? Configuration.getConfig().logFormat + ? Configuration.getConfig()?.logFormat : 'simple'; } - static getLogRotate(): boolean { + static getLogRotate(): boolean | undefined { return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logRotate') - ? Configuration.getConfig().logRotate + ? Configuration.getConfig()?.logRotate : true; } - static getLogMaxFiles(): number | string | undefined { + static getLogMaxFiles(): number | string | false | undefined { return ( Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logMaxFiles') && - Configuration.getConfig().logMaxFiles + Configuration.getConfig()?.logMaxFiles ); } - static getLogMaxSize(): number | string | undefined { + static getLogMaxSize(): number | string | false | undefined { return ( Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logMaxFiles') && - Configuration.getConfig().logMaxSize + Configuration.getConfig()?.logMaxSize ); } - static getLogLevel(): string { + static getLogLevel(): string | undefined { return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logLevel') - ? Configuration.getConfig().logLevel.toLowerCase() + ? Configuration.getConfig()?.logLevel?.toLowerCase() : 'info'; } - static getLogFile(): string { + static getLogFile(): string | undefined { return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logFile') - ? Configuration.getConfig().logFile + ? Configuration.getConfig()?.logFile : 'combined.log'; } - static getLogErrorFile(): string { - Configuration.warnDeprecatedConfigurationKey('errorFile', null, "Use 'logErrorFile' instead"); + static getLogErrorFile(): string | undefined { + Configuration.warnDeprecatedConfigurationKey( + 'errorFile', + undefined, + "Use 'logErrorFile' instead" + ); return Configuration.objectHasOwnProperty(Configuration.getConfig(), 'logErrorFile') - ? Configuration.getConfig().logErrorFile + ? Configuration.getConfig()?.logErrorFile : 'error.log'; } - static getSupervisionUrls(): string | string[] { + static getSupervisionUrls(): string | string[] | undefined { Configuration.warnDeprecatedConfigurationKey( 'supervisionURLs', - null, + undefined, "Use 'supervisionUrls' instead" ); !Configuration.isUndefined(Configuration.getConfig()['supervisionURLs']) && - (Configuration.getConfig().supervisionUrls = Configuration.getConfig()[ - 'supervisionURLs' - ] as string[]); + (Configuration.getConfig().supervisionUrls = Configuration.getConfig()['supervisionURLs'] as + | string + | string[]); // Read conf - return Configuration.getConfig().supervisionUrls; + return Configuration.getConfig()?.supervisionUrls; } - static getSupervisionUrlDistribution(): SupervisionUrlDistribution { + static getSupervisionUrlDistribution(): SupervisionUrlDistribution | undefined { Configuration.warnDeprecatedConfigurationKey( 'distributeStationToTenantEqually', - null, + undefined, "Use 'supervisionUrlDistribution' instead" ); Configuration.warnDeprecatedConfigurationKey( 'distributeStationsToTenantsEqually', - null, + undefined, "Use 'supervisionUrlDistribution' instead" ); return Configuration.objectHasOwnProperty( Configuration.getConfig(), 'supervisionUrlDistribution' ) - ? Configuration.getConfig().supervisionUrlDistribution + ? Configuration.getConfig()?.supervisionUrlDistribution : SupervisionUrlDistribution.ROUND_ROBIN; } @@ -341,7 +349,7 @@ export default class Configuration { } // Read the config file - private static getConfig(): ConfigurationData { + private static getConfig(): ConfigurationData | null { if (!Configuration.configuration) { try { Configuration.configuration = JSON.parse( @@ -362,7 +370,7 @@ export default class Configuration { return Configuration.configuration; } - private static getConfigurationFileWatcher(): fs.FSWatcher { + private static getConfigurationFileWatcher(): fs.FSWatcher | undefined { try { return fs.watch(Configuration.configurationFile, (event, filename): void => { if (filename && event === 'change') { @@ -411,7 +419,7 @@ export default class Configuration { } private static isUndefined(obj: unknown): boolean { - return typeof obj === 'undefined'; + return obj === undefined; } private static handleFileException( diff --git a/src/utils/FileUtils.ts b/src/utils/FileUtils.ts index ccee788b..2e99f52f 100644 --- a/src/utils/FileUtils.ts +++ b/src/utils/FileUtils.ts @@ -31,7 +31,7 @@ export default class FileUtils { } } } - ): fs.FSWatcher { + ): fs.FSWatcher | undefined { if (file) { try { return fs.watch(file, listener); diff --git a/src/utils/Logger.ts b/src/utils/Logger.ts index 7e08136c..46897bb9 100644 --- a/src/utils/Logger.ts +++ b/src/utils/Logger.ts @@ -15,7 +15,7 @@ if (Configuration.getLogRotate() === true) { filename: Utils.insertAt( Configuration.getLogErrorFile(), '-%DATE%', - Configuration.getLogErrorFile().indexOf('.log') + Configuration.getLogErrorFile()?.indexOf('.log') ), level: 'error', ...(logMaxFiles && { maxFiles: logMaxFiles }), @@ -25,7 +25,7 @@ if (Configuration.getLogRotate() === true) { filename: Utils.insertAt( Configuration.getLogFile(), '-%DATE%', - Configuration.getLogFile().indexOf('.log') + Configuration.getLogFile()?.indexOf('.log') ), ...(logMaxFiles && { maxFiles: logMaxFiles }), ...(logMaxSize && { maxSize: logMaxSize }), diff --git a/src/utils/Utils.ts b/src/utils/Utils.ts index 4a9bdb70..5fb5f625 100644 --- a/src/utils/Utils.ts +++ b/src/utils/Utils.ts @@ -184,8 +184,8 @@ export default class Utils { return clone(object); } - public static isIterable(obj: T): boolean { - return obj ? typeof obj[Symbol.iterator] === 'function' : false; + public static isIterable>(obj: T): boolean { + return !Utils.isNullOrUndefined(obj) ? typeof obj[Symbol.iterator] === 'function' : false; } public static isString(value: unknown): boolean { diff --git a/src/worker/WorkerFactory.ts b/src/worker/WorkerFactory.ts index 4e1cea02..465a3eff 100644 --- a/src/worker/WorkerFactory.ts +++ b/src/worker/WorkerFactory.ts @@ -30,7 +30,7 @@ export default class WorkerFactory { workerOptions.poolOptions = workerOptions?.poolOptions ?? ({} as PoolOptions); workerOptions?.messageHandler && (workerOptions.poolOptions.messageHandler = workerOptions.messageHandler); - let workerImplementation: WorkerAbstract = null; + let workerImplementation: WorkerAbstract | null = null; switch (workerProcessType) { case WorkerProcessType.WORKER_SET: workerOptions.elementsPerWorker = -- 2.34.1