Fix workspace sonarlint configuration
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPResponseService.ts
CommitLineData
6c1761d4 1import type { JSONSchemaType } from 'ajv';
844e496b
JB
2import Ajv from 'ajv-draft-04';
3import ajvFormats from 'ajv-formats';
4
5import OCPPError from '../../exception/OCPPError';
6c1761d4
JB
6import type { JsonType } from '../../types/JsonType';
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;
012ae1a9 16 private readonly ajv: Ajv;
10068088 17
08f130a0 18 protected constructor() {
844e496b
JB
19 this.ajv = new Ajv();
20 ajvFormats(this.ajv);
9952c548
JB
21 this.responseHandler.bind(this);
22 this.validateResponsePayload.bind(this);
c0560973
JB
23 }
24
08f130a0 25 public static getInstance<T extends OCPPResponseService>(this: new () => T): T {
1ca780f9 26 if (OCPPResponseService.instance === null) {
08f130a0 27 OCPPResponseService.instance = new this();
9f2e3130 28 }
08f130a0 29 return OCPPResponseService.instance as T;
9f2e3130
JB
30 }
31
844e496b
JB
32 protected validateResponsePayload<T extends JsonType>(
33 chargingStation: ChargingStation,
34 commandName: RequestCommand,
35 schema: JSONSchemaType<T>,
36 payload: T
37 ): boolean {
0638ddd2 38 if (chargingStation.getPayloadSchemaValidation() === false) {
844e496b
JB
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(
01a4dcbb 50 OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
844e496b
JB
51 'Response PDU is invalid',
52 commandName,
53 JSON.stringify(validate.errors, null, 2)
54 );
55 }
56
b52c969d
JB
57 // eslint-disable-next-line @typescript-eslint/no-empty-function
58 protected emptyResponseHandler() {}
59
f7f98c68 60 public abstract responseHandler(
08f130a0 61 chargingStation: ChargingStation,
e7aeea18 62 commandName: RequestCommand,
5cc4b63b
JB
63 payload: JsonType,
64 requestPayload: JsonType
e7aeea18 65 ): Promise<void>;
c0560973 66}