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'; |
06ad945f | 10 | import { OCPP16ServiceUtils } from './1.6/OCPP16ServiceUtils'; |
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); | |
c0560973 JB |
21 | } |
22 | ||
08f130a0 JB |
23 | public static getInstance<T extends OCPPResponseService>(this: new () => T): T { |
24 | if (!OCPPResponseService.instance) { | |
25 | OCPPResponseService.instance = new this(); | |
9f2e3130 | 26 | } |
08f130a0 | 27 | return OCPPResponseService.instance as T; |
9f2e3130 JB |
28 | } |
29 | ||
844e496b JB |
30 | protected validateResponsePayload<T extends JsonType>( |
31 | chargingStation: ChargingStation, | |
32 | commandName: RequestCommand, | |
33 | schema: JSONSchemaType<T>, | |
34 | payload: T | |
35 | ): boolean { | |
36 | if (!chargingStation.getPayloadSchemaValidation()) { | |
37 | return true; | |
38 | } | |
39 | const validate = this.ajv.compile(schema); | |
40 | if (validate(payload)) { | |
41 | return true; | |
42 | } | |
43 | logger.error( | |
44 | `${chargingStation.logPrefix()} ${moduleName}.validateResponsePayload: Response PDU is invalid: %j`, | |
45 | validate.errors | |
46 | ); | |
47 | throw new OCPPError( | |
06ad945f | 48 | OCPP16ServiceUtils.AjvErrorsToErrorType(validate.errors), |
844e496b JB |
49 | 'Response PDU is invalid', |
50 | commandName, | |
51 | JSON.stringify(validate.errors, null, 2) | |
52 | ); | |
53 | } | |
54 | ||
b52c969d JB |
55 | // eslint-disable-next-line @typescript-eslint/no-empty-function |
56 | protected emptyResponseHandler() {} | |
57 | ||
f7f98c68 | 58 | public abstract responseHandler( |
08f130a0 | 59 | chargingStation: ChargingStation, |
e7aeea18 | 60 | commandName: RequestCommand, |
5cc4b63b JB |
61 | payload: JsonType, |
62 | requestPayload: JsonType | |
e7aeea18 | 63 | ): Promise<void>; |
c0560973 | 64 | } |