Fixes to OCA OCPP 2.0.1 JSON schemas
[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
4import OCPPError from '../../exception/OCPPError';
6c1761d4 5import type { JsonType } from '../../types/JsonType';
b0342994 6import type { OCPPVersion } from '../../types/ocpp/OCPPVersion';
6c1761d4 7import type { RequestCommand } from '../../types/ocpp/Requests';
844e496b 8import logger from '../../utils/Logger';
8114d10e 9import type ChargingStation from '../ChargingStation';
cbb3711f 10import { OCPPServiceUtils } from './OCPPServiceUtils';
c0560973 11
e3018bc4
JB
12const moduleName = 'OCPPResponseService';
13
c0560973 14export default abstract class OCPPResponseService {
08f130a0 15 private static instance: OCPPResponseService | null = null;
d270cc87 16 private readonly version: OCPPVersion;
012ae1a9 17 private readonly ajv: Ajv;
10068088 18
d270cc87
JB
19 protected constructor(version: OCPPVersion) {
20 this.version = version;
45988780 21 this.ajv = new Ajv({
98fc1389 22 keywords: ['javaType'],
45988780
JB
23 multipleOfPrecision: 2,
24 });
844e496b 25 ajvFormats(this.ajv);
9952c548
JB
26 this.responseHandler.bind(this);
27 this.validateResponsePayload.bind(this);
c0560973
JB
28 }
29
08f130a0 30 public static getInstance<T extends OCPPResponseService>(this: new () => T): T {
1ca780f9 31 if (OCPPResponseService.instance === null) {
08f130a0 32 OCPPResponseService.instance = new this();
9f2e3130 33 }
08f130a0 34 return OCPPResponseService.instance as T;
9f2e3130
JB
35 }
36
844e496b
JB
37 protected validateResponsePayload<T extends JsonType>(
38 chargingStation: ChargingStation,
39 commandName: RequestCommand,
40 schema: JSONSchemaType<T>,
41 payload: T
42 ): boolean {
0638ddd2 43 if (chargingStation.getPayloadSchemaValidation() === false) {
844e496b
JB
44 return true;
45 }
46 const validate = this.ajv.compile(schema);
47 if (validate(payload)) {
48 return true;
49 }
50 logger.error(
45988780 51 `${chargingStation.logPrefix()} ${moduleName}.validateResponsePayload: Command '${commandName}' response PDU is invalid: %j`,
844e496b
JB
52 validate.errors
53 );
54 throw new OCPPError(
01a4dcbb 55 OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
844e496b
JB
56 'Response PDU is invalid',
57 commandName,
58 JSON.stringify(validate.errors, null, 2)
59 );
60 }
61
81e3cc38 62 protected emptyResponseHandler() {
bd770dde 63 /* This is intentional */
81e3cc38 64 }
b52c969d 65
f7f98c68 66 public abstract responseHandler(
08f130a0 67 chargingStation: ChargingStation,
e7aeea18 68 commandName: RequestCommand,
5cc4b63b
JB
69 payload: JsonType,
70 requestPayload: JsonType
e7aeea18 71 ): Promise<void>;
c0560973 72}