| 1 | import type { JSONSchemaType } from 'ajv'; |
| 2 | import Ajv from 'ajv-draft-04'; |
| 3 | import ajvFormats from 'ajv-formats'; |
| 4 | |
| 5 | import OCPPError from '../../exception/OCPPError'; |
| 6 | import type { JsonType } from '../../types/JsonType'; |
| 7 | import type { RequestCommand } from '../../types/ocpp/Requests'; |
| 8 | import logger from '../../utils/Logger'; |
| 9 | import type ChargingStation from '../ChargingStation'; |
| 10 | import { OCPPServiceUtils } from './OCPPServiceUtils'; |
| 11 | |
| 12 | const moduleName = 'OCPPResponseService'; |
| 13 | |
| 14 | export default abstract class OCPPResponseService { |
| 15 | private static instance: OCPPResponseService | null = null; |
| 16 | private readonly ajv: Ajv; |
| 17 | |
| 18 | protected constructor() { |
| 19 | this.ajv = new Ajv(); |
| 20 | ajvFormats(this.ajv); |
| 21 | this.responseHandler.bind(this); |
| 22 | this.validateResponsePayload.bind(this); |
| 23 | } |
| 24 | |
| 25 | public static getInstance<T extends OCPPResponseService>(this: new () => T): T { |
| 26 | if (OCPPResponseService.instance === null) { |
| 27 | OCPPResponseService.instance = new this(); |
| 28 | } |
| 29 | return OCPPResponseService.instance as T; |
| 30 | } |
| 31 | |
| 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() === false) { |
| 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( |
| 50 | OCPPServiceUtils.ajvErrorsToErrorType(validate.errors), |
| 51 | 'Response PDU is invalid', |
| 52 | commandName, |
| 53 | JSON.stringify(validate.errors, null, 2) |
| 54 | ); |
| 55 | } |
| 56 | |
| 57 | protected emptyResponseHandler() { |
| 58 | /* This is intentional */ |
| 59 | } |
| 60 | |
| 61 | public abstract responseHandler( |
| 62 | chargingStation: ChargingStation, |
| 63 | commandName: RequestCommand, |
| 64 | payload: JsonType, |
| 65 | requestPayload: JsonType |
| 66 | ): Promise<void>; |
| 67 | } |