fix(simulator): fix empty array detection helper semantic
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPServiceUtils.ts
index 15edd6dfef63a731370d62dfa76e466abeeeabed..3fced606ba29e6b003aa1b16c0bafdcb4a3f533e 100644 (file)
@@ -1,6 +1,9 @@
-import type { DefinedError, ErrorObject } from 'ajv';
+import fs from 'node:fs';
+
+import type { DefinedError, ErrorObject, JSONSchemaType } from 'ajv';
 
 import BaseError from '../../exception/BaseError';
+import { FileType } from '../../types/FileType';
 import type { JsonObject, JsonType } from '../../types/JsonType';
 import type { SampledValueTemplate } from '../../types/MeasurandPerPhaseSampledValueTemplates';
 import type { OCPP16StatusNotificationRequest } from '../../types/ocpp/1.6/Requests';
@@ -19,6 +22,7 @@ import {
   type StatusNotificationRequest,
 } from '../../types/ocpp/Requests';
 import Constants from '../../utils/Constants';
+import FileUtils from '../../utils/FileUtils';
 import logger from '../../utils/Logger';
 import Utils from '../../utils/Utils';
 import type ChargingStation from '../ChargingStation';
@@ -164,6 +168,25 @@ export class OCPPServiceUtils {
     }
   }
 
+  protected static parseJsonSchemaFile<T extends JsonType>(
+    filePath: string,
+    ocppVersion: OCPPVersion,
+    moduleName?: string,
+    methodName?: string
+  ): JSONSchemaType<T> {
+    try {
+      return JSON.parse(fs.readFileSync(filePath, 'utf8')) as JSONSchemaType<T>;
+    } catch (error) {
+      FileUtils.handleFileException(
+        filePath,
+        FileType.JsonSchema,
+        error as NodeJS.ErrnoException,
+        OCPPServiceUtils.logPrefix(ocppVersion, moduleName, methodName),
+        { throwError: false }
+      );
+    }
+  }
+
   protected static getSampledValueTemplate(
     chargingStation: ChargingStation,
     connectorId: number,
@@ -195,7 +218,7 @@ export class OCPPServiceUtils {
       chargingStation.getConnectorStatus(connectorId)?.MeterValues;
     for (
       let index = 0;
-      Utils.isEmptyArray(sampledValueTemplates) === false && index < sampledValueTemplates.length;
+      Utils.isNotEmptyArray(sampledValueTemplates) === true && index < sampledValueTemplates.length;
       index++
     ) {
       if (
@@ -261,4 +284,16 @@ export class OCPPServiceUtils {
       ? Math.min(numberValue * options.unitMultiplier, limit)
       : numberValue * options.unitMultiplier;
   }
+
+  private static logPrefix = (
+    ocppVersion: OCPPVersion,
+    moduleName?: string,
+    methodName?: string
+  ): string => {
+    const logMsg =
+      Utils.isNotEmptyString(moduleName) && Utils.isNotEmptyString(methodName)
+        ? ` OCPP ${ocppVersion} | ${moduleName}.${methodName}:`
+        : ` OCPP ${ocppVersion} |`;
+    return Utils.logPrefix(logMsg);
+  };
 }