Commit | Line | Data |
---|---|---|
844e496b JB |
1 | import { JSONSchemaType } from 'ajv'; |
2 | import Ajv from 'ajv-draft-04'; | |
3 | import ajvFormats from 'ajv-formats'; | |
4 | ||
5 | import OCPPError from '../../exception/OCPPError'; | |
5cc4b63b | 6 | import { JsonType } from '../../types/JsonType'; |
c0560973 | 7 | import { 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; |
844e496b | 16 | private 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 { | |
38 | if (!chargingStation.getPayloadSchemaValidation()) { | |
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 | } |