From 1c9de2b93a05cb7e29aaf8d070c9bd1d50731191 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Tue, 8 Aug 2023 00:10:53 +0200 Subject: [PATCH] fix: ensure null or undefined checks in condition MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- .../AutomaticTransactionGenerator.ts | 29 +++++++++---------- src/charging-station/ChargingStation.ts | 4 +-- src/charging-station/Helpers.ts | 8 ++--- src/charging-station/ocpp/OCPPServiceUtils.ts | 21 ++++++++------ .../ui-server/UIWebSocketServer.ts | 4 +-- src/utils/Configuration.ts | 22 +++++++------- 6 files changed, 45 insertions(+), 43 deletions(-) diff --git a/src/charging-station/AutomaticTransactionGenerator.ts b/src/charging-station/AutomaticTransactionGenerator.ts index 1cf949d7..e53026ba 100644 --- a/src/charging-station/AutomaticTransactionGenerator.ts +++ b/src/charging-station/AutomaticTransactionGenerator.ts @@ -230,18 +230,18 @@ export class AutomaticTransactionGenerator extends AsyncResource { ), ); logger.info( - `${this.logPrefix(connectorId)} transaction started with id ${this.chargingStation - .getConnectorStatus(connectorId) - ?.transactionId?.toString()} and will stop in ${formatDurationMilliSeconds( - waitTrxEnd, - )}`, + `${this.logPrefix( + connectorId, + )} transaction started with id ${this.chargingStation.getConnectorStatus(connectorId) + ?.transactionId} and will stop in ${formatDurationMilliSeconds(waitTrxEnd)}`, ); await sleep(waitTrxEnd); // Stop transaction logger.info( - `${this.logPrefix(connectorId)} stop transaction with id ${this.chargingStation - .getConnectorStatus(connectorId) - ?.transactionId?.toString()}`, + `${this.logPrefix( + connectorId, + )} stop transaction with id ${this.chargingStation.getConnectorStatus(connectorId) + ?.transactionId}`, ); await this.stopTransaction(connectorId); } @@ -249,11 +249,10 @@ export class AutomaticTransactionGenerator extends AsyncResource { ++this.connectorsStatus.get(connectorId)!.skippedConsecutiveTransactions!; ++this.connectorsStatus.get(connectorId)!.skippedTransactions!; logger.info( - `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus - .get(connectorId) - ?.skippedConsecutiveTransactions?.toString()}/${this.connectorsStatus - .get(connectorId) - ?.skippedTransactions?.toString()} transaction(s)`, + `${this.logPrefix(connectorId)} skipped consecutively ${this.connectorsStatus.get( + connectorId, + )?.skippedConsecutiveTransactions}/${this.connectorsStatus.get(connectorId) + ?.skippedTransactions} transaction(s)`, ); } this.connectorsStatus.get(connectorId)!.lastRunDate = new Date(); @@ -460,7 +459,7 @@ export class AutomaticTransactionGenerator extends AsyncResource { const transactionId = this.chargingStation.getConnectorStatus(connectorId)?.transactionId; logger.warn( `${this.logPrefix(connectorId)} stopping a not started transaction${ - !isNullOrUndefined(transactionId) ? ` with id ${transactionId?.toString()}` : '' + !isNullOrUndefined(transactionId) ? ` with id ${transactionId}` : '' }`, ); } @@ -477,7 +476,7 @@ export class AutomaticTransactionGenerator extends AsyncResource { private logPrefix = (connectorId?: number): string => { return logPrefix( ` ${this.chargingStation.stationInfo.chargingStationId} | ATG${ - !isNullOrUndefined(connectorId) ? ` on connector #${connectorId!.toString()}` : '' + !isNullOrUndefined(connectorId) ? ` on connector #${connectorId}` : '' }:`, ); }; diff --git a/src/charging-station/ChargingStation.ts b/src/charging-station/ChargingStation.ts index 3cf7c60e..1e3cebf5 100644 --- a/src/charging-station/ChargingStation.ts +++ b/src/charging-station/ChargingStation.ts @@ -366,7 +366,7 @@ export class ChargingStation { public getMaximumPower(stationInfo?: ChargingStationInfo): number { const localStationInfo = stationInfo ?? this.stationInfo; return ( - (localStationInfo['maxPower' as keyof ChargingStationInfo] as number) ?? + (localStationInfo?.['maxPower' as keyof ChargingStationInfo] as number) ?? localStationInfo.maximumPower ); } @@ -1509,7 +1509,7 @@ export class ChargingStation { for (let connectorId = 0; connectorId <= configuredMaxConnectors; connectorId++) { if ( connectorId === 0 && - (!stationTemplate?.Connectors[connectorId] || + (!stationTemplate?.Connectors?.[connectorId] || this.getUseConnectorId0(stationTemplate) === false) ) { continue; diff --git a/src/charging-station/Helpers.ts b/src/charging-station/Helpers.ts index bb3bb5af..068bc6c9 100644 --- a/src/charging-station/Helpers.ts +++ b/src/charging-station/Helpers.ts @@ -262,7 +262,7 @@ export const checkConnectorsConfiguration = ( checkConfiguredMaxConnectors(configuredMaxConnectors, logPrefix, templateFile); const templateMaxConnectors = getMaxNumberOfConnectors(stationTemplate.Connectors!); checkTemplateMaxConnectors(templateMaxConnectors, logPrefix, templateFile); - const templateMaxAvailableConnectors = stationTemplate.Connectors![0] + const templateMaxAvailableConnectors = stationTemplate.Connectors?.[0] ? templateMaxConnectors - 1 : templateMaxConnectors; if ( @@ -645,7 +645,7 @@ const getConfiguredMaxNumberOfConnectors = (stationTemplate: ChargingStationTemp } else if (isUndefined(stationTemplate.numberOfConnectors) === false) { configuredMaxNumberOfConnectors = stationTemplate.numberOfConnectors as number; } else if (stationTemplate.Connectors && !stationTemplate.Evses) { - configuredMaxNumberOfConnectors = stationTemplate.Connectors[0] + configuredMaxNumberOfConnectors = stationTemplate.Connectors?.[0] ? getMaxNumberOfConnectors(stationTemplate.Connectors) - 1 : getMaxNumberOfConnectors(stationTemplate.Connectors); } else if (stationTemplate.Evses && !stationTemplate.Connectors) { @@ -709,7 +709,7 @@ const warnDeprecatedTemplateKey = ( templateFile: string, logMsgToAppend = '', ): void => { - if (!isUndefined(template[key as keyof ChargingStationTemplate])) { + if (!isUndefined(template?.[key as keyof ChargingStationTemplate])) { const logMsg = `Deprecated template key '${key}' usage in file '${templateFile}'${ isNotEmptyString(logMsgToAppend) ? `. ${logMsgToAppend}` : '' }`; @@ -723,7 +723,7 @@ const convertDeprecatedTemplateKey = ( deprecatedKey: string, key?: string, ): void => { - if (!isUndefined(template[deprecatedKey as keyof ChargingStationTemplate])) { + if (!isUndefined(template?.[deprecatedKey as keyof ChargingStationTemplate])) { if (!isUndefined(key)) { (template as unknown as Record)[key!] = template[deprecatedKey as keyof ChargingStationTemplate]; diff --git a/src/charging-station/ocpp/OCPPServiceUtils.ts b/src/charging-station/ocpp/OCPPServiceUtils.ts index d3930db4..b4a7e324 100644 --- a/src/charging-station/ocpp/OCPPServiceUtils.ts +++ b/src/charging-station/ocpp/OCPPServiceUtils.ts @@ -88,9 +88,9 @@ export class OCPPServiceUtils { return true; } else if ( isRequestCommand === true && - chargingStation.stationInfo?.commandsSupport?.outgoingCommands + chargingStation.stationInfo?.commandsSupport?.outgoingCommands?.[command] ) { - return chargingStation.stationInfo?.commandsSupport?.outgoingCommands[command] ?? false; + return chargingStation.stationInfo?.commandsSupport?.outgoingCommands[command]; } logger.error(`${chargingStation.logPrefix()} Unknown outgoing OCPP command '${command}'`); return false; @@ -109,9 +109,9 @@ export class OCPPServiceUtils { return true; } else if ( isIncomingRequestCommand === true && - chargingStation.stationInfo?.commandsSupport?.incomingCommands + chargingStation.stationInfo?.commandsSupport?.incomingCommands?.[command] ) { - return chargingStation.stationInfo?.commandsSupport?.incomingCommands[command] ?? false; + return chargingStation.stationInfo?.commandsSupport?.incomingCommands[command]; } logger.error(`${chargingStation.logPrefix()} Unknown incoming OCPP command '${command}'`); return false; @@ -124,8 +124,11 @@ export class OCPPServiceUtils { const isMessageTrigger = Object.values(MessageTrigger).includes(messageTrigger); if (isMessageTrigger === true && !chargingStation.stationInfo?.messageTriggerSupport) { return true; - } else if (isMessageTrigger === true && chargingStation.stationInfo?.messageTriggerSupport) { - return chargingStation.stationInfo?.messageTriggerSupport[messageTrigger] ?? false; + } else if ( + isMessageTrigger === true && + chargingStation.stationInfo?.messageTriggerSupport?.[messageTrigger] + ) { + return chargingStation.stationInfo?.messageTriggerSupport[messageTrigger]; } logger.error( `${chargingStation.logPrefix()} Unknown incoming OCPP message trigger '${messageTrigger}'`, @@ -377,7 +380,7 @@ export class OCPPServiceUtils { return sampledValueTemplates[index]; } else if ( !phase && - !sampledValueTemplates[index].phase && + !sampledValueTemplates[index]?.phase && sampledValueTemplates[index]?.measurand === measurand && getConfigurationKey( chargingStation, @@ -387,8 +390,8 @@ export class OCPPServiceUtils { return sampledValueTemplates[index]; } else if ( measurand === MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER && - (!sampledValueTemplates[index].measurand || - sampledValueTemplates[index].measurand === measurand) + (!sampledValueTemplates[index]?.measurand || + sampledValueTemplates[index]?.measurand === measurand) ) { return sampledValueTemplates[index]; } diff --git a/src/charging-station/ui-server/UIWebSocketServer.ts b/src/charging-station/ui-server/UIWebSocketServer.ts index 5651ab5a..e322ef8d 100644 --- a/src/charging-station/ui-server/UIWebSocketServer.ts +++ b/src/charging-station/ui-server/UIWebSocketServer.ts @@ -118,7 +118,7 @@ export class UIWebSocketServer extends AbstractUIServer { } public sendResponse(response: ProtocolResponse): void { - const responseId = response[0]; + const responseId = response?.[0]; try { if (this.hasResponseHandler(responseId)) { const ws = this.responseHandlers.get(responseId) as WebSocket; @@ -203,7 +203,7 @@ export class UIWebSocketServer extends AbstractUIServer { return false; } - if (validateUUID(request[0]) === false) { + if (validateUUID(request?.[0]) === false) { logger.error( `${this.logPrefix( moduleName, diff --git a/src/utils/Configuration.ts b/src/utils/Configuration.ts index b9fc7bd6..9a4db77f 100644 --- a/src/utils/Configuration.ts +++ b/src/utils/Configuration.ts @@ -75,9 +75,7 @@ export class Configuration { } public static getAutoReconnectMaxRetries(): number | undefined { - if (hasOwnProp(Configuration.getConfigurationData(), 'autoReconnectMaxRetries')) { - return Configuration.getConfigurationData()?.autoReconnectMaxRetries; - } + return Configuration.getConfigurationData()?.autoReconnectMaxRetries; } public static getStationTemplateUrls(): StationTemplateUrl[] | undefined { @@ -88,7 +86,7 @@ export class Configuration { public static getSupervisionUrls(): string | string[] | undefined { if ( !isUndefined( - Configuration.getConfigurationData()!['supervisionURLs' as keyof ConfigurationData], + Configuration.getConfigurationData()?.['supervisionURLs' as keyof ConfigurationData], ) ) { Configuration.getConfigurationData()!.supervisionUrls = Configuration.getConfigurationData()![ @@ -323,15 +321,15 @@ export class Configuration { "Use 'stationTemplateUrls' instead", ); !isUndefined( - Configuration.getConfigurationData()!['stationTemplateURLs' as keyof ConfigurationData], + Configuration.getConfigurationData()?.['stationTemplateURLs' as keyof ConfigurationData], ) && (Configuration.getConfigurationData()!.stationTemplateUrls = Configuration.getConfigurationData()![ 'stationTemplateURLs' as keyof ConfigurationData ] as StationTemplateUrl[]); - Configuration.getConfigurationData()!.stationTemplateUrls.forEach( + Configuration.getConfigurationData()?.stationTemplateUrls.forEach( (stationTemplateUrl: StationTemplateUrl) => { - if (!isUndefined(stationTemplateUrl['numberOfStation' as keyof StationTemplateUrl])) { + if (!isUndefined(stationTemplateUrl?.['numberOfStation' as keyof StationTemplateUrl])) { console.error( `${chalk.green(Configuration.logPrefix())} ${chalk.red( `Deprecated configuration key 'numberOfStation' usage for template file '${stationTemplateUrl.file}' in 'stationTemplateUrls'. Use 'numberOfStations' instead`, @@ -483,14 +481,16 @@ export class Configuration { ) { if ( sectionName && - !isUndefined(Configuration.getConfigurationData()![sectionName as keyof ConfigurationData]) && + !isUndefined( + Configuration.getConfigurationData()?.[sectionName as keyof ConfigurationData], + ) && !isUndefined( ( - Configuration.getConfigurationData()![sectionName as keyof ConfigurationData] as Record< + Configuration.getConfigurationData()?.[sectionName as keyof ConfigurationData] as Record< string, unknown > - )[key], + )?.[key], ) ) { console.error( @@ -501,7 +501,7 @@ export class Configuration { )}`, ); } else if ( - !isUndefined(Configuration.getConfigurationData()![key as keyof ConfigurationData]) + !isUndefined(Configuration.getConfigurationData()?.[key as keyof ConfigurationData]) ) { console.error( `${chalk.green(Configuration.logPrefix())} ${chalk.red( -- 2.34.1