Migrate all JSON schemas to draft-06 or higher
[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 ajvFormats(this.ajv);
23 this.responseHandler.bind(this);
24 this.validateResponsePayload.bind(this);
25 }
26
27 public static getInstance<T extends OCPPResponseService>(this: new () => T): T {
28 if (OCPPResponseService.instance === null) {
29 OCPPResponseService.instance = new this();
30 }
31 return OCPPResponseService.instance as T;
32 }
33
34 protected validateResponsePayload<T extends JsonType>(
35 chargingStation: ChargingStation,
36 commandName: RequestCommand,
37 schema: JSONSchemaType<T>,
38 payload: T
39 ): boolean {
40 if (chargingStation.getPayloadSchemaValidation() === false) {
41 return true;
42 }
43 const validate = this.ajv.compile(schema);
44 if (validate(payload)) {
45 return true;
46 }
47 logger.error(
48 `${chargingStation.logPrefix()} ${moduleName}.validateResponsePayload: Response PDU is invalid: %j`,
49 validate.errors
50 );
51 throw new OCPPError(
52 OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
53 'Response PDU is invalid',
54 commandName,
55 JSON.stringify(validate.errors, null, 2)
56 );
57 }
58
59 protected emptyResponseHandler() {
60 /* This is intentional */
61 }
62
63 public abstract responseHandler(
64 chargingStation: ChargingStation,
65 commandName: RequestCommand,
66 payload: JsonType,
67 requestPayload: JsonType
68 ): Promise<void>;
69 }