refactor: remove isNullOrDefined() helper
authorJérôme Benoit <jerome.benoit@sap.com>
Fri, 29 Dec 2023 19:07:26 +0000 (20:07 +0100)
committerJérôme Benoit <jerome.benoit@sap.com>
Fri, 29 Dec 2023 19:07:26 +0000 (20:07 +0100)
Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
src/charging-station/Helpers.ts
src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts
src/charging-station/ocpp/OCPPServiceUtils.ts
src/utils/Utils.ts
src/utils/index.ts
tests/utils/Utils.test.ts

index c38248491dbcc2db95464671decaa6109cc0612f..38988d05dff7e9d161b403a2ebe7f4f8118ec010 100644 (file)
@@ -65,7 +65,6 @@ import {
   isEmptyString,
   isNotEmptyArray,
   isNotEmptyString,
-  isNullOrUndefined,
   isUndefined,
   isValidTime,
   logger,
@@ -255,7 +254,7 @@ export const checkTemplate = (
       Constants.DEFAULT_ATG_CONFIGURATION
     )
   }
-  if (isNullOrUndefined(stationTemplate.idTagsFile) || isEmptyString(stationTemplate.idTagsFile)) {
+  if (stationTemplate.idTagsFile == null || isEmptyString(stationTemplate.idTagsFile)) {
     logger.warn(
       `${logPrefix} Missing id tags file in template file ${templateFile}. That can lead to issues with the Automatic Transaction Generator`
     )
@@ -361,10 +360,7 @@ export const initializeConnectorsMapStatus = (
         // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
         connectors.get(connectorId)!.chargingProfiles = []
       }
-    } else if (
-      connectorId > 0 &&
-      isNullOrUndefined(connectors.get(connectorId)?.transactionStarted)
-    ) {
+    } else if (connectorId > 0 && connectors.get(connectorId)?.transactionStarted == null) {
       // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
       initializeConnectorStatus(connectors.get(connectorId)!)
     }
@@ -593,7 +589,7 @@ export const getChargingStationConnectorChargingProfilesPowerLimit = (
       chargingProfiles,
       chargingStation.logPrefix()
     )
-    if (!isNullOrUndefined(result)) {
+    if (result != null) {
       limit = result?.limit
       chargingProfile = result?.chargingProfile
       switch (chargingStation.stationInfo?.currentOutType) {
@@ -605,8 +601,7 @@ export const getChargingStationConnectorChargingProfilesPowerLimit = (
                 chargingStation.getNumberOfPhases(),
                 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
                 chargingStation.stationInfo.voltageOut!,
-                // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-                limit!
+                limit
               )
           break
         case CurrentType.DC:
@@ -614,13 +609,12 @@ export const getChargingStationConnectorChargingProfilesPowerLimit = (
             chargingProfile?.chargingSchedule?.chargingRateUnit === ChargingRateUnitType.WATT
               ? limit
               : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-              DCElectricUtils.power(chargingStation.stationInfo.voltageOut!, limit!)
+              DCElectricUtils.power(chargingStation.stationInfo.voltageOut!, limit)
       }
       const connectorMaximumPower =
         // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
         chargingStation.stationInfo.maximumPower! / chargingStation.powerDivider
-      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-      if (limit! > connectorMaximumPower) {
+      if (limit > connectorMaximumPower) {
         logger.error(
           `${chargingStation.logPrefix()} ${moduleName}.getChargingStationConnectorChargingProfilesPowerLimit: Charging profile id ${chargingProfile?.chargingProfileId} limit ${limit} is greater than connector id ${connectorId} maximum ${connectorMaximumPower}: %j`,
           result
@@ -804,36 +798,26 @@ const getLimitFromChargingProfiles = (
   const connectorStatus = chargingStation.getConnectorStatus(connectorId)!
   for (const chargingProfile of chargingProfiles) {
     const chargingSchedule = chargingProfile.chargingSchedule
-    if (
-      isNullOrUndefined(chargingSchedule?.startSchedule) &&
-      connectorStatus?.transactionStarted === true
-    ) {
+    if (chargingSchedule?.startSchedule == null && connectorStatus?.transactionStarted === true) {
       logger.debug(
         `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} has no startSchedule defined. Trying to set it to the connector current transaction start date`
       )
       // OCPP specifies that if startSchedule is not defined, it should be relative to start of the connector transaction
       chargingSchedule.startSchedule = connectorStatus?.transactionStart
     }
-    if (
-      !isNullOrUndefined(chargingSchedule?.startSchedule) &&
-      !isDate(chargingSchedule?.startSchedule)
-    ) {
+    if (chargingSchedule?.startSchedule != null && !isDate(chargingSchedule?.startSchedule)) {
       logger.warn(
         `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} startSchedule property is not a Date instance. Trying to convert it to a Date instance`
       )
       // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
       chargingSchedule.startSchedule = convertToDate(chargingSchedule?.startSchedule)!
     }
-    if (
-      !isNullOrUndefined(chargingSchedule?.startSchedule) &&
-      isNullOrUndefined(chargingSchedule?.duration)
-    ) {
+    if (chargingSchedule?.startSchedule != null && chargingSchedule?.duration == null) {
       logger.debug(
         `${logPrefix} ${moduleName}.getLimitFromChargingProfiles: Charging profile id ${chargingProfile.chargingProfileId} has no duration defined and will be set to the maximum time allowed`
       )
       // OCPP specifies that if duration is not defined, it should be infinite
-      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-      chargingSchedule.duration = differenceInSeconds(maxTime, chargingSchedule.startSchedule!)
+      chargingSchedule.duration = differenceInSeconds(maxTime, chargingSchedule.startSchedule)
     }
     if (!prepareChargingProfileKind(connectorStatus, chargingProfile, currentDate, logPrefix)) {
       continue
@@ -949,7 +933,7 @@ export const prepareChargingProfileKind = (
       prepareRecurringChargingProfile(chargingProfile, currentDate, logPrefix)
       break
     case ChargingProfileKindType.RELATIVE:
-      if (!isNullOrUndefined(chargingProfile.chargingSchedule.startSchedule)) {
+      if (chargingProfile.chargingSchedule.startSchedule != null) {
         logger.warn(
           `${logPrefix} ${moduleName}.prepareChargingProfileKind: Relative charging profile id ${chargingProfile.chargingProfileId} has a startSchedule property defined. It will be ignored or used if the connector has a transaction started`
         )
@@ -983,8 +967,8 @@ export const canProceedChargingProfile = (
     return false
   }
   if (
-    isNullOrUndefined(chargingProfile.chargingSchedule.startSchedule) ||
-    isNullOrUndefined(chargingProfile.chargingSchedule.duration)
+    chargingProfile.chargingSchedule.startSchedule == null ||
+    chargingProfile.chargingSchedule.duration == null
   ) {
     logger.error(
       `${logPrefix} ${moduleName}.canProceedChargingProfile: Charging profile id ${chargingProfile.chargingProfileId} has no startSchedule or duration defined`
@@ -992,7 +976,7 @@ export const canProceedChargingProfile = (
     return false
   }
   if (
-    !isNullOrUndefined(chargingProfile.chargingSchedule.startSchedule) &&
+    chargingProfile.chargingSchedule.startSchedule != null &&
     !isValidTime(chargingProfile.chargingSchedule.startSchedule)
   ) {
     logger.error(
@@ -1001,7 +985,7 @@ export const canProceedChargingProfile = (
     return false
   }
   if (
-    !isNullOrUndefined(chargingProfile.chargingSchedule.duration) &&
+    chargingProfile.chargingSchedule.duration != null &&
     !Number.isSafeInteger(chargingProfile.chargingSchedule.duration)
   ) {
     logger.error(
@@ -1018,7 +1002,7 @@ const canProceedRecurringChargingProfile = (
 ): boolean => {
   if (
     chargingProfile.chargingProfileKind === ChargingProfileKindType.RECURRING &&
-    isNullOrUndefined(chargingProfile.recurrencyKind)
+    chargingProfile.recurrencyKind == null
   ) {
     logger.error(
       `${logPrefix} ${moduleName}.canProceedRecurringChargingProfile: Recurring charging profile id ${chargingProfile.chargingProfileId} has no recurrencyKind defined`
@@ -1027,7 +1011,7 @@ const canProceedRecurringChargingProfile = (
   }
   if (
     chargingProfile.chargingProfileKind === ChargingProfileKindType.RECURRING &&
-    isNullOrUndefined(chargingProfile.chargingSchedule.startSchedule)
+    chargingProfile.chargingSchedule.startSchedule == null
   ) {
     logger.error(
       `${logPrefix} ${moduleName}.canProceedRecurringChargingProfile: Recurring charging profile id ${chargingProfile.chargingProfileId} has no startSchedule defined`
@@ -1126,7 +1110,7 @@ const checkRecurringChargingProfileDuration = (
   interval: Interval,
   logPrefix: string
 ): void => {
-  if (isNullOrUndefined(chargingProfile.chargingSchedule.duration)) {
+  if (chargingProfile.chargingSchedule.duration == null) {
     logger.warn(
       `${logPrefix} ${moduleName}.checkRecurringChargingProfileDuration: Recurring ${
         chargingProfile.chargingProfileKind
@@ -1139,8 +1123,7 @@ const checkRecurringChargingProfileDuration = (
     )
     chargingProfile.chargingSchedule.duration = differenceInSeconds(interval.end, interval.start)
   } else if (
-    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-    chargingProfile.chargingSchedule.duration! > differenceInSeconds(interval.end, interval.start)
+    chargingProfile.chargingSchedule.duration > differenceInSeconds(interval.end, interval.start)
   ) {
     logger.warn(
       `${logPrefix} ${moduleName}.checkRecurringChargingProfileDuration: Recurring ${
index 94f03ef8b26a4442c34a120212a8775b87866998..f419838896a05dde3c7ab4b3d9a389ba40fc2796 100644 (file)
@@ -105,7 +105,6 @@ import {
   isEmptyArray,
   isNotEmptyArray,
   isNotEmptyString,
-  isNullOrUndefined,
   isUndefined,
   logger,
   sleep
@@ -724,7 +723,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
     let compositeSchedule: OCPP16ChargingSchedule | undefined
     for (const chargingProfile of chargingProfiles) {
       if (
-        isNullOrUndefined(chargingProfile.chargingSchedule?.startSchedule) &&
+        chargingProfile.chargingSchedule?.startSchedule == null &&
         connectorStatus?.transactionStarted === true
       ) {
         logger.debug(
@@ -736,7 +735,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
         chargingProfile.chargingSchedule.startSchedule = connectorStatus?.transactionStart
       }
       if (
-        !isNullOrUndefined(chargingProfile.chargingSchedule?.startSchedule) &&
+        chargingProfile.chargingSchedule?.startSchedule != null &&
         !isDate(chargingProfile.chargingSchedule?.startSchedule)
       ) {
         logger.warn(
@@ -750,8 +749,8 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
         )!
       }
       if (
-        !isNullOrUndefined(chargingProfile.chargingSchedule?.startSchedule) &&
-        isNullOrUndefined(chargingProfile.chargingSchedule?.duration)
+        chargingProfile.chargingSchedule?.startSchedule != null &&
+        chargingProfile.chargingSchedule?.duration == null
       ) {
         logger.debug(
           `${chargingStation.logPrefix()} ${moduleName}.handleRequestGetCompositeSchedule: Charging profile id ${
@@ -761,8 +760,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
         // OCPP specifies that if duration is not defined, it should be infinite
         chargingProfile.chargingSchedule.duration = differenceInSeconds(
           maxTime,
-          // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-          chargingProfile.chargingSchedule.startSchedule!
+          chargingProfile.chargingSchedule.startSchedule
         )
       }
       if (
@@ -826,7 +824,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
     }
     // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
     const connectorStatus = chargingStation.getConnectorStatus(connectorId!)
-    if (!isNullOrUndefined(connectorId) && isNotEmptyArray(connectorStatus?.chargingProfiles)) {
+    if (connectorId != null && isNotEmptyArray(connectorStatus?.chargingProfiles)) {
       // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
       connectorStatus!.chargingProfiles = []
       logger.debug(
@@ -834,7 +832,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
       )
       return OCPP16Constants.OCPP_CLEAR_CHARGING_PROFILE_RESPONSE_ACCEPTED
     }
-    if (isNullOrUndefined(connectorId)) {
+    if (connectorId == null) {
       let clearedCP = false
       if (chargingStation.hasEvses) {
         for (const evseStatus of chargingStation.evses.values()) {
@@ -1123,7 +1121,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
     }
     let { retrieveDate } = commandPayload
     if (
-      !isNullOrUndefined(chargingStation.stationInfo.firmwareStatus) &&
+      chargingStation.stationInfo.firmwareStatus != null &&
       chargingStation.stationInfo.firmwareStatus !== OCPP16FirmwareStatus.Installed
     ) {
       logger.warn(
@@ -1473,7 +1471,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
           return OCPP16Constants.OCPP_TRIGGER_MESSAGE_RESPONSE_ACCEPTED
         case OCPP16MessageTrigger.StatusNotification:
           setTimeout(() => {
-            if (!isNullOrUndefined(connectorId)) {
+            if (connectorId != null) {
               chargingStation.ocppRequestService
                 .requestHandler<OCPP16StatusNotificationRequest, OCPP16StatusNotificationResponse>(
                 chargingStation,
@@ -1481,8 +1479,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
                 {
                   connectorId,
                   errorCode: OCPP16ChargePointErrorCode.NO_ERROR,
-                  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-                  status: chargingStation.getConnectorStatus(connectorId!)?.status
+                  status: chargingStation.getConnectorStatus(connectorId)?.status
                 },
                 {
                   triggerMessage: true
index 6b055bebc7dbb0f52afeeca98e7361cd2c592686..045feade6e88843f486b9ebdc4cf5328f1e3ab54 100644 (file)
@@ -59,7 +59,6 @@ import {
   handleFileException,
   isNotEmptyArray,
   isNotEmptyString,
-  isNullOrUndefined,
   isUndefined,
   logPrefix,
   logger,
@@ -961,17 +960,13 @@ export const buildMeterValue = (
         // Persist previous value on connector
         if (connector != null) {
           if (
-            !isNullOrUndefined(connector.energyActiveImportRegisterValue) &&
-            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-            connector.energyActiveImportRegisterValue! >= 0 &&
-            !isNullOrUndefined(connector.transactionEnergyActiveImportRegisterValue) &&
-            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-            connector.transactionEnergyActiveImportRegisterValue! >= 0
+            connector.energyActiveImportRegisterValue != null &&
+            connector.energyActiveImportRegisterValue >= 0 &&
+            connector.transactionEnergyActiveImportRegisterValue != null &&
+            connector.transactionEnergyActiveImportRegisterValue >= 0
           ) {
-            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-            connector.energyActiveImportRegisterValue! += energyValueRounded
-            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-            connector.transactionEnergyActiveImportRegisterValue! += energyValueRounded
+            connector.energyActiveImportRegisterValue += energyValueRounded
+            connector.transactionEnergyActiveImportRegisterValue += energyValueRounded
           } else {
             connector.energyActiveImportRegisterValue = 0
             connector.transactionEnergyActiveImportRegisterValue = 0
@@ -1185,16 +1180,16 @@ const buildSampledValue = (
   const sampledValuePhase = phase ?? sampledValueTemplate?.phase
   // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
   return {
-    ...(!isNullOrUndefined(sampledValueTemplate.unit) && {
+    ...(sampledValueTemplate.unit != null && {
       unit: sampledValueTemplate.unit
     }),
-    ...(!isNullOrUndefined(sampledValueContext) && { context: sampledValueContext }),
-    ...(!isNullOrUndefined(sampledValueTemplate.measurand) && {
+    ...(sampledValueContext != null && { context: sampledValueContext }),
+    ...(sampledValueTemplate.measurand != null && {
       measurand: sampledValueTemplate.measurand
     }),
-    ...(!isNullOrUndefined(sampledValueLocation) && { location: sampledValueLocation }),
-    ...(!isNullOrUndefined(value) && { value: value.toString() }),
-    ...(!isNullOrUndefined(sampledValuePhase) && { phase: sampledValuePhase })
+    ...(sampledValueLocation != null && { location: sampledValueLocation }),
+    ...(value != null && { value: value.toString() }),
+    ...(sampledValuePhase != null && { phase: sampledValuePhase })
   } as SampledValue
 }
 
index fa82ba1d334836cb4454cabcd6b544564dd0f317..f025d629c8464f4a78d0009362d74f95c4167aa6 100644 (file)
@@ -291,10 +291,6 @@ export const isUndefined = (value: unknown): boolean => {
   return value === undefined
 }
 
-export const isNullOrUndefined = (value: unknown): boolean => {
-  return value == null
-}
-
 export const isEmptyArray = (object: unknown): boolean => {
   return Array.isArray(object) && object.length === 0
 }
index 0e727baa5e99041a289baa44a5fa94f198fe267b..08cdf6ce4c8f6b76ef77960f15094781570bee2a 100644 (file)
@@ -45,7 +45,6 @@ export {
   isEmptyString,
   isNotEmptyArray,
   isNotEmptyString,
-  isNullOrUndefined,
   isUndefined,
   isValidTime,
   logPrefix,
index bbb847069e102603eeef6b4e40c1af346dfedd2c..1c6400edec0c75ec3fb1b5ef414dce1805e7a422 100644 (file)
@@ -24,7 +24,6 @@ import {
   isIterable,
   isNotEmptyArray,
   isNotEmptyString,
-  isNullOrUndefined,
   isObject,
   isUndefined,
   isValidTime,
@@ -368,19 +367,6 @@ await describe('Utils test suite', async () => {
     expect(isUndefined(new WeakSet())).toBe(false)
   })
 
-  await it('Verify isNullOrUndefined()', () => {
-    expect(isNullOrUndefined(undefined)).toBe(true)
-    expect(isNullOrUndefined(null)).toBe(true)
-    expect(isNullOrUndefined('')).toBe(false)
-    expect(isNullOrUndefined(0)).toBe(false)
-    expect(isNullOrUndefined({})).toBe(false)
-    expect(isNullOrUndefined([])).toBe(false)
-    expect(isNullOrUndefined(new Map())).toBe(false)
-    expect(isNullOrUndefined(new Set())).toBe(false)
-    expect(isNullOrUndefined(new WeakMap())).toBe(false)
-    expect(isNullOrUndefined(new WeakSet())).toBe(false)
-  })
-
   await it('Verify isEmptyArray()', () => {
     expect(isEmptyArray([])).toBe(true)
     expect(isEmptyArray([1, 2])).toBe(false)