AjvErrorsToErrorType -> ajvErrorsToErrorType
[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 }
22
23 public static getInstance<T extends OCPPResponseService>(this: new () => T): T {
24 if (!OCPPResponseService.instance) {
25 OCPPResponseService.instance = new this();
26 }
27 return OCPPResponseService.instance as T;
28 }
29
30 protected validateResponsePayload<T extends JsonType>(
31 chargingStation: ChargingStation,
32 commandName: RequestCommand,
33 schema: JSONSchemaType<T>,
34 payload: T
35 ): boolean {
36 if (!chargingStation.getPayloadSchemaValidation()) {
37 return true;
38 }
39 const validate = this.ajv.compile(schema);
40 if (validate(payload)) {
41 return true;
42 }
43 logger.error(
44 `${chargingStation.logPrefix()} ${moduleName}.validateResponsePayload: Response PDU is invalid: %j`,
45 validate.errors
46 );
47 throw new OCPPError(
48 OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
49 'Response PDU is invalid',
50 commandName,
51 JSON.stringify(validate.errors, null, 2)
52 );
53 }
54
55 // eslint-disable-next-line @typescript-eslint/no-empty-function
56 protected emptyResponseHandler() {}
57
58 public abstract responseHandler(
59 chargingStation: ChargingStation,
60 commandName: RequestCommand,
61 payload: JsonType,
62 requestPayload: JsonType
63 ): Promise<void>;
64 }