Strict null check fixes
authorJérôme Benoit <jerome.benoit@sap.com>
Wed, 25 Jan 2023 18:37:20 +0000 (19:37 +0100)
committerJérôme Benoit <jerome.benoit@sap.com>
Wed, 25 Jan 2023 18:37:20 +0000 (19:37 +0100)
Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
src/charging-station/Bootstrap.ts
src/charging-station/ChargingStation.ts
src/charging-station/ocpp/OCPPRequestService.ts
src/charging-station/ui-server/UIHttpServer.ts
src/charging-station/ui-server/UIWebSocketServer.ts
src/charging-station/ui-server/ui-services/AbstractUIService.ts
src/charging-station/ui-server/ui-services/UIServiceFactory.ts
src/utils/CircularArray.ts

index 8a161e54a66e210c9fd856b3cf06295e12db9b5a..ce1290dbc27462ad1d7cfc746954bb1191184f63 100644 (file)
@@ -39,7 +39,7 @@ enum exitCodes {
 export class Bootstrap {
   private static instance: Bootstrap | null = null;
   private workerImplementation: WorkerAbstract<ChargingStationWorkerData> | null;
-  private readonly uiServer!: AbstractUIServer;
+  private readonly uiServer!: AbstractUIServer | null;
   private readonly storage!: Storage;
   private numberOfChargingStationTemplates!: number | undefined;
   private numberOfChargingStations!: number;
index 639123abe9f814631de87409c7fbc7ad66c5a3b0..9d69f038ea23dcf64f235e004e19b9b425dbfb8e 100644 (file)
@@ -100,12 +100,12 @@ export default class ChargingStation {
   public started: boolean;
   public starting: boolean;
   public authorizedTagsCache: AuthorizedTagsCache;
-  public automaticTransactionGenerator!: AutomaticTransactionGenerator;
-  public ocppConfiguration!: ChargingStationOcppConfiguration | null;
+  public automaticTransactionGenerator!: AutomaticTransactionGenerator | undefined;
+  public ocppConfiguration!: ChargingStationOcppConfiguration | undefined;
   public wsConnection!: WebSocket | null;
   public readonly connectors: Map<number, ConnectorStatus>;
   public readonly requests: Map<string, CachedRequest>;
-  public performanceStatistics!: PerformanceStatistics;
+  public performanceStatistics!: PerformanceStatistics | undefined;
   public heartbeatSetInterval!: NodeJS.Timeout;
   public ocppRequestService!: OCPPRequestService;
   public bootNotificationRequest!: BootNotificationRequest;
@@ -501,7 +501,7 @@ export default class ChargingStation {
       if (this.starting === false) {
         this.starting = true;
         if (this.getEnableStatistics() === true) {
-          this.performanceStatistics.start();
+          this.performanceStatistics?.start();
         }
         this.openWSConnection();
         // Monitor charging station template file
@@ -529,9 +529,9 @@ export default class ChargingStation {
                   this.startAutomaticTransactionGenerator();
                 }
                 if (this.getEnableStatistics() === true) {
-                  this.performanceStatistics.restart();
+                  this.performanceStatistics?.restart();
                 } else {
-                  this.performanceStatistics.stop();
+                  this.performanceStatistics?.stop();
                 }
                 // FIXME?: restart heartbeat and WebSocket ping when their interval values have changed
               } catch (error) {
@@ -561,7 +561,7 @@ export default class ChargingStation {
         await this.stopMessageSequence(reason);
         this.closeWSConnection();
         if (this.getEnableStatistics() === true) {
-          this.performanceStatistics.stop();
+          this.performanceStatistics?.stop();
         }
         this.sharedLRUCache.deleteChargingStationConfiguration(this.configurationFileHash);
         this.templateFileWatcher?.close();
@@ -712,10 +712,10 @@ export default class ChargingStation {
     );
     if (!Utils.isEmptyArray(connectorIds)) {
       for (const connectorId of connectorIds) {
-        this.automaticTransactionGenerator.startConnector(connectorId);
+        this.automaticTransactionGenerator?.startConnector(connectorId);
       }
     } else {
-      this.automaticTransactionGenerator.start();
+      this.automaticTransactionGenerator?.start();
     }
     parentPort?.postMessage(MessageChannelUtils.buildUpdatedMessage(this));
   }
@@ -863,14 +863,14 @@ export default class ChargingStation {
     stationInfo.ocppVersion = stationTemplate?.ocppVersion ?? OCPPVersion.VERSION_16;
     ChargingStationUtils.createSerialNumber(stationTemplate, stationInfo);
     if (!Utils.isEmptyArray(stationTemplate?.power)) {
-      stationTemplate.power = stationTemplate?.power as number[];
+      stationTemplate.power = stationTemplate.power as number[];
       const powerArrayRandomIndex = Math.floor(Utils.secureRandom() * stationTemplate.power.length);
       stationInfo.maximumPower =
         stationTemplate?.powerUnit === PowerUnits.KILO_WATT
           ? stationTemplate.power[powerArrayRandomIndex] * 1000
           : stationTemplate.power[powerArrayRandomIndex];
     } else {
-      stationTemplate.power = stationTemplate.power as number;
+      stationTemplate.power = stationTemplate?.power as number;
       stationInfo.maximumPower =
         stationTemplate?.powerUnit === PowerUnits.KILO_WATT
           ? stationTemplate.power * 1000
@@ -930,17 +930,17 @@ export default class ChargingStation {
     return stationInfo;
   }
 
-  private getStationInfoFromFile(): ChargingStationInfo | null {
-    let stationInfo: ChargingStationInfo | null = null;
+  private getStationInfoFromFile(): ChargingStationInfo | undefined {
+    let stationInfo: ChargingStationInfo | undefined;
     this.getStationInfoPersistentConfiguration() &&
-      (stationInfo = this.getConfigurationFromFile()?.stationInfo ?? null);
+      (stationInfo = this.getConfigurationFromFile()?.stationInfo);
     stationInfo && ChargingStationUtils.createStationInfoHash(stationInfo);
     return stationInfo;
   }
 
   private getStationInfo(): ChargingStationInfo {
     const stationInfoFromTemplate: ChargingStationInfo = this.getStationInfoFromTemplate();
-    const stationInfoFromFile: ChargingStationInfo | null = this.getStationInfoFromFile();
+    const stationInfoFromFile: ChargingStationInfo | undefined = this.getStationInfoFromFile();
     // Priority: charging station info from template > charging station info from configuration file > charging station info attribute
     if (stationInfoFromFile?.templateHash === stationInfoFromTemplate.templateHash) {
       if (this.stationInfo?.infoHash === stationInfoFromFile?.infoHash) {
@@ -1315,8 +1315,8 @@ export default class ChargingStation {
     }
   }
 
-  private getConfigurationFromFile(): ChargingStationConfiguration | null {
-    let configuration: ChargingStationConfiguration | null = null;
+  private getConfigurationFromFile(): ChargingStationConfiguration | undefined {
+    let configuration: ChargingStationConfiguration | undefined;
     if (this.configurationFile && fs.existsSync(this.configurationFile)) {
       try {
         if (this.sharedLRUCache.hasChargingStationConfiguration(this.configurationFileHash)) {
@@ -1394,12 +1394,12 @@ export default class ChargingStation {
     }
   }
 
-  private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration | null {
-    return this.getTemplateFromFile()?.Configuration ?? null;
+  private getOcppConfigurationFromTemplate(): ChargingStationOcppConfiguration | undefined {
+    return this.getTemplateFromFile()?.Configuration;
   }
 
-  private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | null {
-    let configuration: ChargingStationConfiguration | null = null;
+  private getOcppConfigurationFromFile(): ChargingStationOcppConfiguration | undefined {
+    let configuration: ChargingStationConfiguration | undefined;
     if (this.getOcppPersistentConfiguration() === true) {
       const configurationFromFile = this.getConfigurationFromFile();
       configuration = configurationFromFile?.configurationKey && configurationFromFile;
@@ -1408,8 +1408,8 @@ export default class ChargingStation {
     return configuration;
   }
 
-  private getOcppConfiguration(): ChargingStationOcppConfiguration | null {
-    let ocppConfiguration: ChargingStationOcppConfiguration | null =
+  private getOcppConfiguration(): ChargingStationOcppConfiguration | undefined {
+    let ocppConfiguration: ChargingStationOcppConfiguration | undefined =
       this.getOcppConfigurationFromFile();
     if (!ocppConfiguration) {
       ocppConfiguration = this.getOcppConfigurationFromTemplate();
@@ -1514,7 +1514,7 @@ export default class ChargingStation {
           case MessageType.CALL_MESSAGE:
             [, , commandName, commandPayload] = request as IncomingRequest;
             if (this.getEnableStatistics() === true) {
-              this.performanceStatistics.addRequestStatistic(commandName, messageType);
+              this.performanceStatistics?.addRequestStatistic(commandName, messageType);
             }
             logger.debug(
               `${this.logPrefix()} << Command '${commandName}' received request payload: ${JSON.stringify(
@@ -2047,8 +2047,10 @@ export default class ChargingStation {
     }
   }
 
-  private getAutomaticTransactionGeneratorConfigurationFromTemplate(): AutomaticTransactionGeneratorConfiguration | null {
-    return this.getTemplateFromFile()?.AutomaticTransactionGenerator ?? null;
+  private getAutomaticTransactionGeneratorConfigurationFromTemplate():
+    | AutomaticTransactionGeneratorConfiguration
+    | undefined {
+    return this.getTemplateFromFile()?.AutomaticTransactionGenerator;
   }
 
   private initializeConnectorStatus(connectorId: number): void {
index fc4410f8658653b16e5305b8251441fe0577ae55..67faed54fc4610a8d98b419cbe30474eba1108b9 100644 (file)
@@ -232,7 +232,7 @@ export default abstract class OCPPRequestService {
       return Utils.promiseWithTimeout(
         new Promise((resolve, reject) => {
           if (chargingStation.getEnableStatistics() === true) {
-            chargingStation.performanceStatistics.addRequestStatistic(commandName, messageType);
+            chargingStation.performanceStatistics?.addRequestStatistic(commandName, messageType);
           }
           const messageToSend = this.buildMessageToSend(
             chargingStation,
@@ -306,7 +306,7 @@ export default abstract class OCPPRequestService {
            */
           function responseCallback(payload: JsonType, requestPayload: JsonType): void {
             if (chargingStation.getEnableStatistics() === true) {
-              chargingStation.performanceStatistics.addRequestStatistic(
+              chargingStation.performanceStatistics?.addRequestStatistic(
                 commandName,
                 MessageType.CALL_RESULT_MESSAGE
               );
@@ -338,7 +338,7 @@ export default abstract class OCPPRequestService {
            */
           function errorCallback(error: OCPPError, requestStatistic = true): void {
             if (requestStatistic === true && chargingStation.getEnableStatistics() === true) {
-              chargingStation.performanceStatistics.addRequestStatistic(
+              chargingStation.performanceStatistics?.addRequestStatistic(
                 commandName,
                 MessageType.CALL_ERROR_MESSAGE
               );
index 87f10a5eab41ef30ce19d0dd5211320900d9697e..f475b8efbac54af6d9fb900920ea32b6298d7fcf 100644 (file)
@@ -110,7 +110,7 @@ export default class UIHttpServer extends AbstractUIServer {
             const body = JSON.parse(Buffer.concat(bodyBuffer).toString()) as RequestPayload;
             this.uiServices
               .get(version)
-              .requestHandler(this.buildProtocolRequest(uuid, procedureName, body ?? {}))
+              ?.requestHandler(this.buildProtocolRequest(uuid, procedureName, body ?? {}))
               .catch(() => {
                 /* Error caught by AbstractUIService */
               });
index e217305f2e1e42f9644ad25f1467aceab57fa12b..d6240e31ef2dadb43f7ccbc2121a6442903252be 100644 (file)
@@ -49,7 +49,7 @@ export default class UIWebSocketServer extends AbstractUIServer {
         this.responseHandlers.set(requestId, ws);
         this.uiServices
           .get(version)
-          .requestHandler(request)
+          ?.requestHandler(request)
           .catch(() => {
             /* Error caught by AbstractUIService */
           });
index 5a418b9d4baf53cc3032efee92e808971da58626..1dd0ee274da3adb320134e66a4f3798dfe932ace 100644 (file)
@@ -92,7 +92,7 @@ export default abstract class AbstractUIService {
       // Log
       logger.error(`${this.logPrefix(moduleName, 'messageHandler')} Handle request error:`, error);
       responsePayload = {
-        hashIds: requestPayload.hashIds,
+        hashIds: requestPayload?.hashIds,
         status: ResponseStatus.FAILURE,
         command,
         requestPayload,
index 551869f06eccea332351c5600b5dccb3272275c4..9f2d448b3eac147748791e9a197c57bd9a1a0809 100644 (file)
@@ -11,12 +11,10 @@ export default class UIServiceFactory {
   public static getUIServiceImplementation(
     version: ProtocolVersion,
     uiServer: AbstractUIServer
-  ): AbstractUIService | null {
+  ): AbstractUIService {
     switch (version) {
       case ProtocolVersion['0.0.1']:
         return new UIService001(uiServer);
-      default:
-        return null;
     }
   }
 }
index d4e965e7adf22bdc5c571b3701db9541a7631c23..5fdeeaad1f7e57c2dae60d0c6fe976d623c942bd 100644 (file)
@@ -47,7 +47,7 @@ export class CircularArray<T> extends Array<T> {
 
   public splice(start: number, deleteCount?: number, ...items: T[]): T[] {
     let itemsRemoved: T[];
-    if (arguments.length >= 3 && typeof deleteCount !== 'undefined') {
+    if (arguments.length >= 3 && deleteCount !== undefined) {
       itemsRemoved = super.splice(start, deleteCount);
       // FIXME: that makes the items insert not in place
       this.push(...items);