From: Jérôme Benoit Date: Fri, 29 Dec 2023 18:48:33 +0000 (+0100) Subject: refactor: cleanup isNullOrUndefined usage X-Git-Tag: v1.2.31~18 X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=aa63c9b772ff17bce2febf68a57720eab96d5f8e;p=e-mobility-charging-stations-simulator.git refactor: cleanup isNullOrUndefined usage Signed-off-by: Jérôme Benoit --- diff --git a/src/charging-station/ChargingStation.ts b/src/charging-station/ChargingStation.ts index df029c3a..a1bb33a9 100644 --- a/src/charging-station/ChargingStation.ts +++ b/src/charging-station/ChargingStation.ts @@ -143,7 +143,6 @@ import { handleFileException, isNotEmptyArray, isNotEmptyString, - isNullOrUndefined, isUndefined, logPrefix, logger, @@ -274,7 +273,7 @@ export class ChargingStation extends EventEmitter { } public inUnknownState (): boolean { - return isNullOrUndefined(this?.bootNotificationResponse?.status) + return this?.bootNotificationResponse?.status == null } public inPendingState (): boolean { @@ -348,7 +347,7 @@ export class ChargingStation extends EventEmitter { public getConnectorMaximumAvailablePower (connectorId: number): number { let connectorAmperageLimitationPowerLimit: number | undefined if ( - !isNullOrUndefined(this.getAmperageLimitation()) && + this.getAmperageLimitation() != null && // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.getAmperageLimitation()! < this.stationInfo.maximumAmperage! ) { @@ -570,7 +569,7 @@ export class ChargingStation extends EventEmitter { return } else if ( this.getConnectorStatus(connectorId)?.transactionStarted === true && - isNullOrUndefined(this.getConnectorStatus(connectorId)?.transactionId) + this.getConnectorStatus(connectorId)?.transactionId == null ) { logger.error( `${this.logPrefix()} Trying to start MeterValues on connector id ${connectorId} with no transaction id` @@ -735,10 +734,7 @@ export class ChargingStation extends EventEmitter { if (!checkChargingStation(this, this.logPrefix())) { return } - if ( - !isNullOrUndefined(this.stationInfo.supervisionUser) && - !isNullOrUndefined(this.stationInfo.supervisionPassword) - ) { + if (this.stationInfo.supervisionUser != null && this.stationInfo.supervisionPassword != null) { options.auth = `${this.stationInfo.supervisionUser}:${this.stationInfo.supervisionPassword}` } if (params?.closeOpened === true) { @@ -796,7 +792,7 @@ export class ChargingStation extends EventEmitter { } public getAutomaticTransactionGeneratorConfiguration (): AutomaticTransactionGeneratorConfiguration { - if (isNullOrUndefined(this.automaticTransactionGeneratorConfiguration)) { + if (this.automaticTransactionGeneratorConfiguration == null) { let automaticTransactionGeneratorConfiguration: | AutomaticTransactionGeneratorConfiguration | undefined @@ -817,8 +813,7 @@ export class ChargingStation extends EventEmitter { ...automaticTransactionGeneratorConfiguration } } - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - return this.automaticTransactionGeneratorConfiguration! + return this.automaticTransactionGeneratorConfiguration } public getAutomaticTransactionGeneratorStatuses (): Status[] | undefined { @@ -885,7 +880,7 @@ export class ChargingStation extends EventEmitter { transactionId, // eslint-disable-next-line @typescript-eslint/no-non-null-assertion meterStop: this.getEnergyActiveImportRegisterByTransactionId(transactionId!, true), - ...(isNullOrUndefined(reason) && { reason }) + ...(reason != null && { reason }) }) } @@ -1046,7 +1041,7 @@ export class ChargingStation extends EventEmitter { this.wsConnection?.send(message, (error?: Error) => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion isRequest && PerformanceStatistics.endMeasure(commandName!, beginId!) - if (isNullOrUndefined(error)) { + if (error == null) { logger.debug( `${this.logPrefix()} >> Buffered ${getMessageTypeString( messageType @@ -1145,10 +1140,10 @@ export class ChargingStation extends EventEmitter { }, stationTemplate?.firmwareUpgrade ?? {} ) - stationInfo.resetTime = !isNullOrUndefined(stationTemplate?.resetTime) - ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - secondsToMilliseconds(stationTemplate.resetTime!) - : Constants.CHARGING_STATION_DEFAULT_RESET_TIME + stationInfo.resetTime = + stationTemplate?.resetTime != null + ? secondsToMilliseconds(stationTemplate.resetTime) + : Constants.CHARGING_STATION_DEFAULT_RESET_TIME return stationInfo } @@ -1234,16 +1229,14 @@ export class ChargingStation extends EventEmitter { .exec(this.stationInfo.firmwareVersion!) // eslint-disable-next-line @typescript-eslint/no-non-null-assertion ?.slice(1, patternGroup! + 1) - if (!isNullOrUndefined(match)) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const patchLevelIndex = match!.length - 1 - // prettier-ignore - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - match![patchLevelIndex] = (convertToInt(match![patchLevelIndex]) + - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - this.stationInfo.firmwareUpgrade!.versionUpgrade!.step!).toString() - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - this.stationInfo.firmwareVersion = match!.join('.') + if (match != null) { + const patchLevelIndex = match.length - 1 + match[patchLevelIndex] = ( + convertToInt(match[patchLevelIndex]) + + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + this.stationInfo.firmwareUpgrade!.versionUpgrade!.step! + ).toString() + this.stationInfo.firmwareVersion = match.join('.') } } this.saveStationInfo() @@ -1301,17 +1294,17 @@ export class ChargingStation extends EventEmitter { } private initializeOcppConfiguration (): void { - if (isNullOrUndefined(getConfigurationKey(this, StandardParametersKey.HeartbeatInterval))) { + if (getConfigurationKey(this, StandardParametersKey.HeartbeatInterval) == null) { addConfigurationKey(this, StandardParametersKey.HeartbeatInterval, '0') } - if (isNullOrUndefined(getConfigurationKey(this, StandardParametersKey.HeartBeatInterval))) { + if (getConfigurationKey(this, StandardParametersKey.HeartBeatInterval) == null) { addConfigurationKey(this, StandardParametersKey.HeartBeatInterval, '0', { visible: false }) } if ( this.stationInfo?.supervisionUrlOcppConfiguration === true && isNotEmptyString(this.stationInfo?.supervisionUrlOcppKey) && // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - isNullOrUndefined(getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!)) + getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!) == null ) { addConfigurationKey( this, @@ -1324,7 +1317,7 @@ export class ChargingStation extends EventEmitter { this.stationInfo?.supervisionUrlOcppConfiguration === false && isNotEmptyString(this.stationInfo?.supervisionUrlOcppKey) && // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - !isNullOrUndefined(getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!)) + getConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!) != null ) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion deleteConfigurationKey(this, this.stationInfo.supervisionUrlOcppKey!, { save: false }) @@ -1332,7 +1325,7 @@ export class ChargingStation extends EventEmitter { if ( isNotEmptyString(this.stationInfo?.amperageLimitationOcppKey) && // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - isNullOrUndefined(getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey!)) + getConfigurationKey(this, this.stationInfo.amperageLimitationOcppKey!) == null ) { addConfigurationKey( this, @@ -1343,9 +1336,7 @@ export class ChargingStation extends EventEmitter { (this.stationInfo.maximumAmperage! * getAmperageLimitationUnitDivider(this.stationInfo)).toString() ) } - if ( - isNullOrUndefined(getConfigurationKey(this, StandardParametersKey.SupportedFeatureProfiles)) - ) { + if (getConfigurationKey(this, StandardParametersKey.SupportedFeatureProfiles) == null) { addConfigurationKey( this, StandardParametersKey.SupportedFeatureProfiles, @@ -1359,18 +1350,14 @@ export class ChargingStation extends EventEmitter { { readonly: true }, { overwrite: true } ) - if ( - isNullOrUndefined(getConfigurationKey(this, StandardParametersKey.MeterValuesSampledData)) - ) { + if (getConfigurationKey(this, StandardParametersKey.MeterValuesSampledData) == null) { addConfigurationKey( this, StandardParametersKey.MeterValuesSampledData, MeterValueMeasurand.ENERGY_ACTIVE_IMPORT_REGISTER ) } - if ( - isNullOrUndefined(getConfigurationKey(this, StandardParametersKey.ConnectorPhaseRotation)) - ) { + if (getConfigurationKey(this, StandardParametersKey.ConnectorPhaseRotation) == null) { const connectorsPhaseRotation: string[] = [] if (this.hasEvses) { for (const evseStatus of this.evses.values()) { @@ -1395,18 +1382,16 @@ export class ChargingStation extends EventEmitter { connectorsPhaseRotation.toString() ) } - if ( - isNullOrUndefined(getConfigurationKey(this, StandardParametersKey.AuthorizeRemoteTxRequests)) - ) { + if (getConfigurationKey(this, StandardParametersKey.AuthorizeRemoteTxRequests) == null) { addConfigurationKey(this, StandardParametersKey.AuthorizeRemoteTxRequests, 'true') } if ( - isNullOrUndefined(getConfigurationKey(this, StandardParametersKey.LocalAuthListEnabled)) && + getConfigurationKey(this, StandardParametersKey.LocalAuthListEnabled) == null && hasFeatureProfile(this, SupportedFeatureProfiles.LocalAuthListManagement) === true ) { addConfigurationKey(this, StandardParametersKey.LocalAuthListEnabled, 'false') } - if (isNullOrUndefined(getConfigurationKey(this, StandardParametersKey.ConnectionTimeOut))) { + if (getConfigurationKey(this, StandardParametersKey.ConnectionTimeOut) == null) { addConfigurationKey( this, StandardParametersKey.ConnectionTimeOut, diff --git a/src/charging-station/broadcast-channel/UIServiceWorkerBroadcastChannel.ts b/src/charging-station/broadcast-channel/UIServiceWorkerBroadcastChannel.ts index 93586cee..11127ec9 100644 --- a/src/charging-station/broadcast-channel/UIServiceWorkerBroadcastChannel.ts +++ b/src/charging-station/broadcast-channel/UIServiceWorkerBroadcastChannel.ts @@ -6,7 +6,7 @@ import { type ResponsePayload, ResponseStatus } from '../../types/index.js' -import { isNullOrUndefined, logger } from '../../utils/index.js' +import { logger } from '../../utils/index.js' import type { AbstractUIService } from '../ui-server/ui-services/AbstractUIService.js' const moduleName = 'UIServiceWorkerBroadcastChannel' @@ -78,7 +78,7 @@ export class UIServiceWorkerBroadcastChannel extends WorkerBroadcastChannel { } return undefined }) - .filter((hashId) => !isNullOrUndefined(hashId)) as string[], + .filter((hashId) => hashId != null) as string[], ...(responsesStatus === ResponseStatus.FAILURE && { hashIdsFailed: this.responses .get(uuid) @@ -88,7 +88,7 @@ export class UIServiceWorkerBroadcastChannel extends WorkerBroadcastChannel { } return undefined }) - .filter((hashId) => !isNullOrUndefined(hashId)) as string[] + .filter((hashId) => hashId != null) as string[] }), ...(responsesStatus === ResponseStatus.FAILURE && { responsesFailed: this.responses @@ -99,7 +99,7 @@ export class UIServiceWorkerBroadcastChannel extends WorkerBroadcastChannel { } return undefined }) - .filter((response) => !isNullOrUndefined(response)) as BroadcastChannelResponsePayload[] + .filter((response) => response != null) as BroadcastChannelResponsePayload[] }) } } diff --git a/src/charging-station/ocpp/1.6/OCPP16ResponseService.ts b/src/charging-station/ocpp/1.6/OCPP16ResponseService.ts index d7d9ce0a..f3855a1a 100644 --- a/src/charging-station/ocpp/1.6/OCPP16ResponseService.ts +++ b/src/charging-station/ocpp/1.6/OCPP16ResponseService.ts @@ -51,7 +51,7 @@ import { type SetChargingProfileResponse, type UnlockConnectorResponse } from '../../../types/index.js' -import { Constants, convertToInt, isNullOrUndefined, logger } from '../../../utils/index.js' +import { Constants, convertToInt, logger } from '../../../utils/index.js' import { OCPPResponseService } from '../OCPPResponseService.js' const moduleName = 'OCPP16ResponseService' @@ -462,7 +462,7 @@ export class OCPP16ResponseService extends OCPPResponseService { } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const authorizeConnectorStatus = chargingStation.getConnectorStatus(authorizeConnectorId!) - const authorizeConnectorIdDefined = !isNullOrUndefined(authorizeConnectorId) + const authorizeConnectorIdDefined = authorizeConnectorId != null if (payload.idTagInfo.status === OCPP16AuthorizationStatus.ACCEPTED) { if (authorizeConnectorIdDefined) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion @@ -705,7 +705,7 @@ export class OCPP16ResponseService extends OCPPResponseService { const transactionConnectorId = chargingStation.getConnectorIdByTransactionId( requestPayload.transactionId ) - if (isNullOrUndefined(transactionConnectorId)) { + if (transactionConnectorId == null) { logger.error( `${chargingStation.logPrefix()} Trying to stop a non existing transaction with id ${ requestPayload.transactionId @@ -725,28 +725,24 @@ export class OCPP16ResponseService extends OCPPResponseService { meterValue: [ OCPP16ServiceUtils.buildTransactionEndMeterValue( chargingStation, - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - transactionConnectorId!, + transactionConnectorId, requestPayload.meterStop ) ] })) if ( !chargingStation.isChargingStationAvailable() || - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - !chargingStation.isConnectorAvailable(transactionConnectorId!) + !chargingStation.isConnectorAvailable(transactionConnectorId) ) { await OCPP16ServiceUtils.sendAndSetConnectorStatus( chargingStation, - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - transactionConnectorId!, + transactionConnectorId, OCPP16ChargePointStatus.Unavailable ) } else { await OCPP16ServiceUtils.sendAndSetConnectorStatus( chargingStation, - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - transactionConnectorId!, + transactionConnectorId, OCPP16ChargePointStatus.Available ) } @@ -754,16 +750,15 @@ export class OCPP16ResponseService extends OCPPResponseService { chargingStation.powerDivider-- } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - resetConnectorStatus(chargingStation.getConnectorStatus(transactionConnectorId!)!) - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - chargingStation.stopMeterValues(transactionConnectorId!) + resetConnectorStatus(chargingStation.getConnectorStatus(transactionConnectorId)!) + chargingStation.stopMeterValues(transactionConnectorId) const logMsg = `${chargingStation.logPrefix()} Transaction with id ${ requestPayload.transactionId } STOPPED on ${ chargingStation.stationInfo.chargingStationId }#${transactionConnectorId} with status '${payload.idTagInfo?.status}'` if ( - isNullOrUndefined(payload.idTagInfo) || + payload.idTagInfo == null || payload.idTagInfo?.status === OCPP16AuthorizationStatus.ACCEPTED ) { logger.info(logMsg) diff --git a/src/charging-station/ocpp/1.6/OCPP16ServiceUtils.ts b/src/charging-station/ocpp/1.6/OCPP16ServiceUtils.ts index c234a5ec..2d31c051 100644 --- a/src/charging-station/ocpp/1.6/OCPP16ServiceUtils.ts +++ b/src/charging-station/ocpp/1.6/OCPP16ServiceUtils.ts @@ -37,7 +37,7 @@ import { type OCPP16SupportedFeatureProfiles, OCPPVersion } from '../../../types/index.js' -import { isNotEmptyArray, isNullOrUndefined, logger, roundTo } from '../../../utils/index.js' +import { isNotEmptyArray, logger, roundTo } from '../../../utils/index.js' import { OCPPServiceUtils } from '../OCPPServiceUtils.js' export class OCPP16ServiceUtils extends OCPPServiceUtils { @@ -149,7 +149,7 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils { connectorId: number, cp: OCPP16ChargingProfile ): void { - if (isNullOrUndefined(chargingStation.getConnectorStatus(connectorId)?.chargingProfiles)) { + if (chargingStation.getConnectorStatus(connectorId)?.chargingProfiles == null) { logger.error( `${chargingStation.logPrefix()} Trying to set a charging profile on connector id ${connectorId} with an uninitialized charging profiles array attribute, applying deferred initialization` ) diff --git a/src/charging-station/ocpp/OCPPRequestService.ts b/src/charging-station/ocpp/OCPPRequestService.ts index e98ebdfa..e78f71c5 100644 --- a/src/charging-station/ocpp/OCPPRequestService.ts +++ b/src/charging-station/ocpp/OCPPRequestService.ts @@ -27,7 +27,6 @@ import { cloneObject, formatDurationMilliSeconds, handleSendMessageError, - isNullOrUndefined, logger } from '../../utils/index.js' type Ajv = _Ajv.default @@ -436,7 +435,7 @@ export abstract class OCPPRequestService { chargingStation.wsConnection?.send(messageToSend, (error?: Error) => { PerformanceStatistics.endMeasure(commandName, beginId) clearTimeout(sendTimeout) - if (isNullOrUndefined(error)) { + if (error == null) { logger.debug( `${chargingStation.logPrefix()} >> Command '${commandName}' sent ${OCPPServiceUtils.getMessageTypeString( messageType diff --git a/src/charging-station/ui-server/ui-services/AbstractUIService.ts b/src/charging-station/ui-server/ui-services/AbstractUIService.ts index 499e9699..84740101 100644 --- a/src/charging-station/ui-server/ui-services/AbstractUIService.ts +++ b/src/charging-station/ui-server/ui-services/AbstractUIService.ts @@ -12,7 +12,7 @@ import { type ResponsePayload, ResponseStatus } from '../../../types/index.js' -import { isNotEmptyArray, isNullOrUndefined, logger } from '../../../utils/index.js' +import { isNotEmptyArray, logger } from '../../../utils/index.js' import { Bootstrap } from '../../Bootstrap.js' import { UIServiceWorkerBroadcastChannel } from '../../broadcast-channel/UIServiceWorkerBroadcastChannel.js' import type { AbstractUIServer } from '../AbstractUIServer.js' @@ -108,9 +108,9 @@ export abstract class AbstractUIService { errorDetails: (error as OCPPError).details } } - if (!isNullOrUndefined(responsePayload)) { + if (responsePayload != null) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - return this.uiServer.buildProtocolResponse(messageId!, responsePayload!) + return this.uiServer.buildProtocolResponse(messageId!, responsePayload) } } @@ -175,7 +175,7 @@ export abstract class AbstractUIService { ) return undefined }) - ?.filter((hashId) => !isNullOrUndefined(hashId)) as string[] + ?.filter((hashId) => hashId != null) as string[] } else { delete payload.hashIds } diff --git a/src/utils/ChargingStationConfigurationUtils.ts b/src/utils/ChargingStationConfigurationUtils.ts index 1869fdbf..6a2cd8e0 100644 --- a/src/utils/ChargingStationConfigurationUtils.ts +++ b/src/utils/ChargingStationConfigurationUtils.ts @@ -1,4 +1,3 @@ -import { isNullOrUndefined } from './Utils.js' import type { ChargingStation } from '../charging-station/index.js' import type { ChargingStationAutomaticTransactionGeneratorConfiguration, @@ -12,10 +11,9 @@ export const buildChargingStationAutomaticTransactionGeneratorConfiguration = ( ): ChargingStationAutomaticTransactionGeneratorConfiguration => { return { automaticTransactionGenerator: chargingStation.getAutomaticTransactionGeneratorConfiguration(), - ...(!isNullOrUndefined(chargingStation.automaticTransactionGenerator?.connectorsStatus) && { + ...(chargingStation.automaticTransactionGenerator?.connectorsStatus != null && { automaticTransactionGeneratorStatuses: [ - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - ...chargingStation.automaticTransactionGenerator!.connectorsStatus.values() + ...chargingStation.automaticTransactionGenerator.connectorsStatus.values() ] }) } diff --git a/src/utils/StatisticUtils.ts b/src/utils/StatisticUtils.ts index bccebbe0..cef15f52 100644 --- a/src/utils/StatisticUtils.ts +++ b/src/utils/StatisticUtils.ts @@ -1,4 +1,4 @@ -import { isEmptyArray, isNullOrUndefined } from './Utils.js' +import { isEmptyArray } from './Utils.js' /** * Computes the average of the given data set. @@ -54,7 +54,7 @@ export const nthPercentile = (dataSet: number[], percentile: number): number => } const percentileIndexBase = (percentile / 100) * (sortedDataSet.length - 1) const percentileIndexInteger = Math.floor(percentileIndexBase) - if (!isNullOrUndefined(sortedDataSet[percentileIndexInteger + 1])) { + if (sortedDataSet[percentileIndexInteger + 1] != null) { return ( sortedDataSet[percentileIndexInteger] + (percentileIndexBase - percentileIndexInteger) * diff --git a/src/utils/Utils.ts b/src/utils/Utils.ts index 291787d9..fa82ba1d 100644 --- a/src/utils/Utils.ts +++ b/src/utils/Utils.ts @@ -209,7 +209,7 @@ export const extractTimeSeriesValues = (timeSeries: TimestampedData[]): number[] } export const isObject = (item: unknown): boolean => { - return !isNullOrUndefined(item) && typeof item === 'object' && !Array.isArray(item) + return item != null && typeof item === 'object' && !Array.isArray(item) } type CloneableData = @@ -268,11 +268,11 @@ export const hasOwnProp = (object: unknown, property: PropertyKey): boolean => { } export const isCFEnvironment = (): boolean => { - return !isNullOrUndefined(env.VCAP_APPLICATION) + return env.VCAP_APPLICATION != null } export const isIterable = (obj: T): boolean => { - return !isNullOrUndefined(obj) ? typeof obj[Symbol.iterator as keyof T] === 'function' : false + return obj != null ? typeof obj[Symbol.iterator as keyof T] === 'function' : false } const isString = (value: unknown): boolean => { @@ -280,7 +280,7 @@ const isString = (value: unknown): boolean => { } export const isEmptyString = (value: unknown): boolean => { - return isNullOrUndefined(value) || (isString(value) && (value as string).trim().length === 0) + return value == null || (isString(value) && (value as string).trim().length === 0) } export const isNotEmptyString = (value: unknown): boolean => {