Linter fixes
[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
78202038 4import { OCPPServiceUtils } from './OCPPServiceUtils';
844e496b 5import OCPPError from '../../exception/OCPPError';
b3fc3ff5 6import type { JsonObject, JsonType } from '../../types/JsonType';
b0342994 7import type { OCPPVersion } from '../../types/ocpp/OCPPVersion';
b3fc3ff5 8import type { IncomingRequestCommand, 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;
d270cc87 16 private readonly version: OCPPVersion;
012ae1a9 17 private readonly ajv: Ajv;
b3fc3ff5
JB
18 public abstract jsonIncomingRequestResponseSchemas: Map<
19 IncomingRequestCommand,
20 JSONSchemaType<JsonObject>
21 >;
10068088 22
d270cc87
JB
23 protected constructor(version: OCPPVersion) {
24 this.version = version;
45988780 25 this.ajv = new Ajv({
98fc1389 26 keywords: ['javaType'],
45988780
JB
27 multipleOfPrecision: 2,
28 });
844e496b 29 ajvFormats(this.ajv);
9952c548
JB
30 this.responseHandler.bind(this);
31 this.validateResponsePayload.bind(this);
c0560973
JB
32 }
33
08f130a0 34 public static getInstance<T extends OCPPResponseService>(this: new () => T): T {
1ca780f9 35 if (OCPPResponseService.instance === null) {
08f130a0 36 OCPPResponseService.instance = new this();
9f2e3130 37 }
08f130a0 38 return OCPPResponseService.instance as T;
9f2e3130
JB
39 }
40
844e496b
JB
41 protected validateResponsePayload<T extends JsonType>(
42 chargingStation: ChargingStation,
43 commandName: RequestCommand,
44 schema: JSONSchemaType<T>,
45 payload: T
46 ): boolean {
0638ddd2 47 if (chargingStation.getPayloadSchemaValidation() === false) {
844e496b
JB
48 return true;
49 }
50 const validate = this.ajv.compile(schema);
51 if (validate(payload)) {
52 return true;
53 }
54 logger.error(
45988780 55 `${chargingStation.logPrefix()} ${moduleName}.validateResponsePayload: Command '${commandName}' response PDU is invalid: %j`,
844e496b
JB
56 validate.errors
57 );
58 throw new OCPPError(
01a4dcbb 59 OCPPServiceUtils.ajvErrorsToErrorType(validate.errors),
844e496b
JB
60 'Response PDU is invalid',
61 commandName,
62 JSON.stringify(validate.errors, null, 2)
63 );
64 }
65
81e3cc38 66 protected emptyResponseHandler() {
bd770dde 67 /* This is intentional */
81e3cc38 68 }
b52c969d 69
f7f98c68 70 public abstract responseHandler(
08f130a0 71 chargingStation: ChargingStation,
e7aeea18 72 commandName: RequestCommand,
5cc4b63b
JB
73 payload: JsonType,
74 requestPayload: JsonType
e7aeea18 75 ): Promise<void>;
c0560973 76}