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