Fixes to OCA OCPP 2.0.1 JSON schemas
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPResponseService.ts
1 import Ajv, { type JSONSchemaType } from 'ajv';
2 import ajvFormats from 'ajv-formats';
3
4 import OCPPError from '../../exception/OCPPError';
5 import type { JsonType } from '../../types/JsonType';
6 import type { OCPPVersion } from '../../types/ocpp/OCPPVersion';
7 import type { RequestCommand } from '../../types/ocpp/Requests';
8 import logger from '../../utils/Logger';
9 import type ChargingStation from '../ChargingStation';
10 import { OCPPServiceUtils } from './OCPPServiceUtils';
11
12 const moduleName = 'OCPPResponseService';
13
14 export default abstract class OCPPResponseService {
15 private static instance: OCPPResponseService | null = null;
16 private readonly version: OCPPVersion;
17 private readonly ajv: Ajv;
18
19 protected constructor(version: OCPPVersion) {
20 this.version = version;
21 this.ajv = new Ajv({
22 keywords: ['javaType'],
23 multipleOfPrecision: 2,
24 });
25 ajvFormats(this.ajv);
26 this.responseHandler.bind(this);
27 this.validateResponsePayload.bind(this);
28 }
29
30 public static getInstance<T extends OCPPResponseService>(this: new () => T): T {
31 if (OCPPResponseService.instance === null) {
32 OCPPResponseService.instance = new this();
33 }
34 return OCPPResponseService.instance as T;
35 }
36
37 protected validateResponsePayload<T extends JsonType>(
38 chargingStation: ChargingStation,
39 commandName: RequestCommand,
40 schema: JSONSchemaType<T>,
41 payload: T
42 ): boolean {
43 if (chargingStation.getPayloadSchemaValidation() === false) {
44 return true;
45 }
46 const validate = this.ajv.compile(schema);
47 if (validate(payload)) {
48 return true;
49 }
50 logger.error(
51 `${chargingStation.logPrefix()} ${moduleName}.validateResponsePayload: Command '${commandName}' response PDU is invalid: %j`,
52 validate.errors
53 );
54 throw new OCPPError(
55 OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
56 'Response PDU is invalid',
57 commandName,
58 JSON.stringify(validate.errors, null, 2)
59 );
60 }
61
62 protected emptyResponseHandler() {
63 /* This is intentional */
64 }
65
66 public abstract responseHandler(
67 chargingStation: ChargingStation,
68 commandName: RequestCommand,
69 payload: JsonType,
70 requestPayload: JsonType
71 ): Promise<void>;
72 }