Add error handling to JSON schemas file reading
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / 2.0 / OCPP20ServiceUtils.ts
CommitLineData
edd13439 1// Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved.
953d6b02 2
130783a7
JB
3import fs from 'node:fs';
4import path from 'node:path';
5import { fileURLToPath } from 'node:url';
6
7import type { JSONSchemaType } from 'ajv';
8
9import { FileType } from '../../../types/FileType';
10import type { JsonType } from '../../../types/JsonType';
11import { OCPPVersion } from '../../../types/ocpp/OCPPVersion';
12import FileUtils from '../../../utils/FileUtils';
953d6b02
JB
13import { OCPPServiceUtils } from '../OCPPServiceUtils';
14
130783a7
JB
15export class OCPP20ServiceUtils extends OCPPServiceUtils {
16 public static parseJsonSchemaFile<T extends JsonType>(relativePath: string): JSONSchemaType<T> {
17 const filePath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), relativePath);
18 try {
19 return JSON.parse(fs.readFileSync(filePath, 'utf8')) as JSONSchemaType<T>;
20 } catch (error) {
21 FileUtils.handleFileException(
22 OCPPServiceUtils.logPrefix(OCPPVersion.VERSION_20),
23 FileType.JsonSchema,
24 filePath,
25 error as NodeJS.ErrnoException,
26 { throwError: false }
27 );
28 }
29 }
30}