Requests PDU validation (#139)
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPResponseService.ts
CommitLineData
844e496b
JB
1import { JSONSchemaType } from 'ajv';
2import Ajv from 'ajv-draft-04';
3import ajvFormats from 'ajv-formats';
4
5import OCPPError from '../../exception/OCPPError';
5cc4b63b 6import { JsonType } from '../../types/JsonType';
844e496b 7import { ErrorType } from '../../types/ocpp/ErrorType';
c0560973 8import { RequestCommand } from '../../types/ocpp/Requests';
844e496b 9import logger from '../../utils/Logger';
8114d10e 10import type ChargingStation from '../ChargingStation';
c0560973 11
e3018bc4
JB
12const moduleName = 'OCPPResponseService';
13
c0560973 14export default abstract class OCPPResponseService {
08f130a0 15 private static instance: OCPPResponseService | null = null;
844e496b 16 private ajv: Ajv;
10068088 17
08f130a0 18 protected constructor() {
844e496b
JB
19 this.ajv = new Ajv();
20 ajvFormats(this.ajv);
c0560973
JB
21 }
22
08f130a0
JB
23 public static getInstance<T extends OCPPResponseService>(this: new () => T): T {
24 if (!OCPPResponseService.instance) {
25 OCPPResponseService.instance = new this();
9f2e3130 26 }
08f130a0 27 return OCPPResponseService.instance as T;
9f2e3130
JB
28 }
29
844e496b
JB
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 ErrorType.FORMATION_VIOLATION,
49 'Response PDU is invalid',
50 commandName,
51 JSON.stringify(validate.errors, null, 2)
52 );
53 }
54
b52c969d
JB
55 // eslint-disable-next-line @typescript-eslint/no-empty-function
56 protected emptyResponseHandler() {}
57
f7f98c68 58 public abstract responseHandler(
08f130a0 59 chargingStation: ChargingStation,
e7aeea18 60 commandName: RequestCommand,
5cc4b63b
JB
61 payload: JsonType,
62 requestPayload: JsonType
e7aeea18 63 ): Promise<void>;
c0560973 64}