refactor(simulator): switch utils to internal module export/import
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPResponseService.ts
CommitLineData
d270cc87 1import Ajv, { type JSONSchemaType } from 'ajv';
844e496b
JB
2import ajvFormats from 'ajv-formats';
3
2896e06d
JB
4import { OCPPServiceUtils } from './internal';
5import type { ChargingStation } from '../../charging-station';
268a74bb
JB
6import { OCPPError } from '../../exception';
7import type {
8 IncomingRequestCommand,
9 JsonObject,
10 JsonType,
11 OCPPVersion,
12 RequestCommand,
13} from '../../types';
60a74391 14import { logger } from '../../utils';
c0560973 15
e3018bc4
JB
16const moduleName = 'OCPPResponseService';
17
268a74bb 18export abstract class OCPPResponseService {
08f130a0 19 private static instance: OCPPResponseService | null = null;
d270cc87 20 private readonly version: OCPPVersion;
012ae1a9 21 private readonly ajv: Ajv;
b3fc3ff5
JB
22 public abstract jsonIncomingRequestResponseSchemas: Map<
23 IncomingRequestCommand,
24 JSONSchemaType<JsonObject>
25 >;
10068088 26
d270cc87
JB
27 protected constructor(version: OCPPVersion) {
28 this.version = version;
45988780 29 this.ajv = new Ajv({
98fc1389 30 keywords: ['javaType'],
45988780
JB
31 multipleOfPrecision: 2,
32 });
844e496b 33 ajvFormats(this.ajv);
9952c548
JB
34 this.responseHandler.bind(this);
35 this.validateResponsePayload.bind(this);
c0560973
JB
36 }
37
08f130a0 38 public static getInstance<T extends OCPPResponseService>(this: new () => T): T {
1ca780f9 39 if (OCPPResponseService.instance === null) {
08f130a0 40 OCPPResponseService.instance = new this();
9f2e3130 41 }
08f130a0 42 return OCPPResponseService.instance as T;
9f2e3130
JB
43 }
44
844e496b
JB
45 protected validateResponsePayload<T extends JsonType>(
46 chargingStation: ChargingStation,
47 commandName: RequestCommand,
48 schema: JSONSchemaType<T>,
49 payload: T
50 ): boolean {
0638ddd2 51 if (chargingStation.getPayloadSchemaValidation() === false) {
844e496b
JB
52 return true;
53 }
54 const validate = this.ajv.compile(schema);
55 if (validate(payload)) {
56 return true;
57 }
58 logger.error(
45988780 59 `${chargingStation.logPrefix()} ${moduleName}.validateResponsePayload: Command '${commandName}' response PDU is invalid: %j`,
844e496b
JB
60 validate.errors
61 );
62 throw new OCPPError(
01a4dcbb 63 OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
844e496b
JB
64 'Response PDU is invalid',
65 commandName,
66 JSON.stringify(validate.errors, null, 2)
67 );
68 }
69
81e3cc38 70 protected emptyResponseHandler() {
bd770dde 71 /* This is intentional */
81e3cc38 72 }
b52c969d 73
f7f98c68 74 public abstract responseHandler(
08f130a0 75 chargingStation: ChargingStation,
e7aeea18 76 commandName: RequestCommand,
5cc4b63b
JB
77 payload: JsonType,
78 requestPayload: JsonType
e7aeea18 79 ): Promise<void>;
c0560973 80}