Add error handling to JSON schemas file reading
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / 1.6 / OCPP16ServiceUtils.ts
index 65fc51c527302969e3335b61533390ae415a4737..d09a8548d28e0545e949fd7c9913637e7ee0dd69 100644 (file)
@@ -1,7 +1,15 @@
 // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
 
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import type { JSONSchemaType } from 'ajv';
+
 import OCPPError from '../../../exception/OCPPError';
 import { CurrentType, Voltage } from '../../../types/ChargingStationTemplate';
+import { FileType } from '../../../types/FileType';
+import type { JsonType } from '../../../types/JsonType';
 import type {
   MeasurandPerPhaseSampledValueTemplates,
   SampledValueTemplate,
@@ -26,8 +34,10 @@ import {
   OCPP16RequestCommand,
 } from '../../../types/ocpp/1.6/Requests';
 import { ErrorType } from '../../../types/ocpp/ErrorType';
+import { OCPPVersion } from '../../../types/ocpp/OCPPVersion';
 import Constants from '../../../utils/Constants';
 import { ACElectricUtils, DCElectricUtils } from '../../../utils/ElectricUtils';
+import FileUtils from '../../../utils/FileUtils';
 import logger from '../../../utils/Logger';
 import Utils from '../../../utils/Utils';
 import type ChargingStation from '../../ChargingStation';
@@ -779,6 +789,21 @@ export class OCPP16ServiceUtils extends OCPPServiceUtils {
     !cpReplaced && chargingStation.getConnectorStatus(connectorId)?.chargingProfiles?.push(cp);
   }
 
+  public static parseJsonSchemaFile<T extends JsonType>(relativePath: string): JSONSchemaType<T> {
+    const filePath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), relativePath);
+    try {
+      return JSON.parse(fs.readFileSync(filePath, 'utf8')) as JSONSchemaType<T>;
+    } catch (error) {
+      FileUtils.handleFileException(
+        OCPPServiceUtils.logPrefix(OCPPVersion.VERSION_16),
+        FileType.JsonSchema,
+        filePath,
+        error as NodeJS.ErrnoException,
+        { throwError: false }
+      );
+    }
+  }
+
   private static buildSampledValue(
     sampledValueTemplate: SampledValueTemplate,
     value: number,