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