Merge branch 'master' into feature/rawmessagelogs
[e-mobility-charging-stations-simulator.git] / src / charging-station / ocpp / OCPPResponseService.ts
index 0a1cd0c610a117ad9c7b0af8211c6ef2efe037c5..d13a7d15aee2ca30a3eb79c4abec531937dcf0b1 100644 (file)
@@ -1,12 +1,32 @@
-import ChargingStation from '../ChargingStation';
+import type ChargingStation from '../ChargingStation';
+import { JsonType } from '../../types/JsonType';
 import { RequestCommand } from '../../types/ocpp/Requests';
 
 export default abstract class OCPPResponseService {
-  protected chargingStation: ChargingStation;
+  private static readonly instances: Map<string, OCPPResponseService> = new Map<
+    string,
+    OCPPResponseService
+  >();
 
-  constructor(chargingStation: ChargingStation) {
+  protected readonly chargingStation: ChargingStation;
+
+  protected constructor(chargingStation: ChargingStation) {
     this.chargingStation = chargingStation;
   }
 
-  public abstract handleResponse(commandName: RequestCommand, payload: Record<string, unknown> | string, requestPayload: Record<string, unknown>): Promise<void>;
+  public static getInstance<T extends OCPPResponseService>(
+    this: new (chargingStation: ChargingStation) => T,
+    chargingStation: ChargingStation
+  ): T {
+    if (!OCPPResponseService.instances.has(chargingStation.hashId)) {
+      OCPPResponseService.instances.set(chargingStation.hashId, new this(chargingStation));
+    }
+    return OCPPResponseService.instances.get(chargingStation.hashId) as T;
+  }
+
+  public abstract handleResponse(
+    commandName: RequestCommand,
+    payload: JsonType | string,
+    requestPayload: JsonType
+  ): Promise<void>;
 }