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