94a943d7c5439ed7f77936d3e464fa6b81443eab
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPResponseService.ts
1 import { JSONSchemaType } from 'ajv';
2 import Ajv from 'ajv-draft-04';
3 import ajvFormats from 'ajv-formats';
4
5 import OCPPError from '../../exception/OCPPError';
6 import { JsonType } from '../../types/JsonType';
7 import { 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 ajv: Ajv;
17
18 protected constructor() {
19 this.ajv = new Ajv();
20 ajvFormats(this.ajv);
21 this.responseHandler.bind(this);
22 this.validateResponsePayload.bind(this);
23 }
24
25 public static getInstance<T extends OCPPResponseService>(this: new () => T): T {
26 if (OCPPResponseService.instance === null) {
27 OCPPResponseService.instance = new this();
28 }
29 return OCPPResponseService.instance as T;
30 }
31
32 protected validateResponsePayload<T extends JsonType>(
33 chargingStation: ChargingStation,
34 commandName: RequestCommand,
35 schema: JSONSchemaType<T>,
36 payload: T
37 ): boolean {
38 if (!chargingStation.getPayloadSchemaValidation()) {
39 return true;
40 }
41 const validate = this.ajv.compile(schema);
42 if (validate(payload)) {
43 return true;
44 }
45 logger.error(
46 `${chargingStation.logPrefix()} ${moduleName}.validateResponsePayload: Response PDU is invalid: %j`,
47 validate.errors
48 );
49 throw new OCPPError(
50 OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
51 'Response PDU is invalid',
52 commandName,
53 JSON.stringify(validate.errors, null, 2)
54 );
55 }
56
57 // eslint-disable-next-line @typescript-eslint/no-empty-function
58 protected emptyResponseHandler() {}
59
60 public abstract responseHandler(
61 chargingStation: ChargingStation,
62 commandName: RequestCommand,
63 payload: JsonType,
64 requestPayload: JsonType
65 ): Promise<void>;
66 }