refactor: cleanup unneeded type casting
authorJérôme Benoit <jerome.benoit@sap.com>
Sat, 20 Jan 2024 20:09:22 +0000 (21:09 +0100)
committerJérôme Benoit <jerome.benoit@sap.com>
Sat, 20 Jan 2024 20:09:22 +0000 (21:09 +0100)
Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
13 files changed:
src/charging-station/Bootstrap.ts
src/charging-station/ChargingStation.ts
src/charging-station/broadcast-channel/ChargingStationWorkerBroadcastChannel.ts
src/charging-station/ocpp/1.6/OCPP16IncomingRequestService.ts
src/charging-station/ocpp/1.6/OCPP16RequestService.ts
src/charging-station/ocpp/1.6/OCPP16ResponseService.ts
src/charging-station/ocpp/2.0/OCPP20IncomingRequestService.ts
src/charging-station/ocpp/2.0/OCPP20RequestService.ts
src/charging-station/ocpp/2.0/OCPP20ResponseService.ts
src/charging-station/ocpp/OCPPIncomingRequestService.ts
src/charging-station/ocpp/OCPPRequestService.ts
src/charging-station/ocpp/OCPPResponseService.ts
src/charging-station/ui-server/UIHttpServer.ts

index 6ee606862cb170e8204faa60086bcc1100158543..f09864d4ed66d935960084061359fe6ca7af3799 100644 (file)
@@ -4,9 +4,10 @@ import { EventEmitter } from 'node:events'
 import { dirname, extname, join } from 'node:path'
 import process, { exit } from 'node:process'
 import { fileURLToPath } from 'node:url'
+import type { Worker } from 'worker_threads'
 
 import chalk from 'chalk'
-import { availableParallelism } from 'poolifier'
+import { type MessageHandler, availableParallelism } from 'poolifier'
 
 import { waitChargingStationEvents } from './Helpers.js'
 import type { AbstractUIServer } from './ui-server/AbstractUIServer.js'
@@ -274,7 +275,7 @@ export class Bootstrap extends EventEmitter {
         poolMinSize: workerConfiguration.poolMinSize!,
         elementsPerWorker: elementsPerWorker ?? (workerConfiguration.elementsPerWorker as number),
         poolOptions: {
-          messageHandler: this.messageHandler.bind(this) as (message: unknown) => void,
+          messageHandler: this.messageHandler.bind(this) as MessageHandler<Worker>,
           workerOptions: { resourceLimits: workerConfiguration.resourceLimits }
         }
       }
index 79d2c7537b7c415dd98223edf39b7204860ad144..4656444f643c82130968fc96769f82f3503166e6 100644 (file)
@@ -768,26 +768,21 @@ export class ChargingStation extends EventEmitter {
     )
 
     // Handle WebSocket message
-    this.wsConnection.on(
-      'message',
-      this.onMessage.bind(this) as (this: WebSocket, data: RawData, isBinary: boolean) => void
-    )
+    // FIXME
+    // eslint-disable-next-line @typescript-eslint/no-misused-promises
+    this.wsConnection.on('message', this.onMessage.bind(this))
     // Handle WebSocket error
-    this.wsConnection.on(
-      'error',
-      this.onError.bind(this) as (this: WebSocket, error: Error) => void
-    )
+    this.wsConnection.on('error', this.onError.bind(this))
     // Handle WebSocket close
-    this.wsConnection.on(
-      'close',
-      this.onClose.bind(this) as (this: WebSocket, code: number, reason: Buffer) => void
-    )
+    this.wsConnection.on('close', this.onClose.bind(this))
     // Handle WebSocket open
-    this.wsConnection.on('open', this.onOpen.bind(this) as (this: WebSocket) => void)
+    // FIXME
+    // eslint-disable-next-line @typescript-eslint/no-misused-promises
+    this.wsConnection.on('open', this.onOpen.bind(this))
     // Handle WebSocket ping
-    this.wsConnection.on('ping', this.onPing.bind(this) as (this: WebSocket, data: Buffer) => void)
+    this.wsConnection.on('ping', this.onPing.bind(this))
     // Handle WebSocket pong
-    this.wsConnection.on('pong', this.onPong.bind(this) as (this: WebSocket, data: Buffer) => void)
+    this.wsConnection.on('pong', this.onPong.bind(this))
   }
 
   public closeWSConnection (): void {
@@ -1805,7 +1800,7 @@ export class ChargingStation extends EventEmitter {
     }
   }
 
-  private async onClose (code: WebSocketCloseEventStatusCode, reason: Buffer): Promise<void> {
+  private onClose (code: WebSocketCloseEventStatusCode, reason: Buffer): void {
     switch (code) {
       // Normal close
       case WebSocketCloseEventStatusCode.CLOSE_NORMAL:
@@ -1824,7 +1819,7 @@ export class ChargingStation extends EventEmitter {
             code
           )}' and reason '${reason.toString()}'`
         )
-        this.started && (await this.reconnect())
+        this.started && this.reconnect().catch(Constants.EMPTY_FUNCTION)
         break
     }
     this.emit(ChargingStationEvents.updated)
index 20f347fc48e2e920c342be8d920e5668206cc49a..d85430f4c16fa6558e63077635b7635b14f32a09 100644 (file)
@@ -256,7 +256,7 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne
     this.onmessageerror = this.messageErrorHandler.bind(this) as (message: unknown) => void
   }
 
-  private async requestHandler (messageEvent: MessageEvent): Promise<void> {
+  private requestHandler (messageEvent: MessageEvent): void {
     const validatedMessageEvent = this.validateMessageEvent(messageEvent)
     if (validatedMessageEvent === false) {
       return
@@ -281,40 +281,42 @@ export class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChanne
     let responsePayload: BroadcastChannelResponsePayload | undefined
     // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
     let commandResponse: CommandResponse | void
-    try {
-      commandResponse = await this.commandHandler(command, requestPayload)
-      if (commandResponse == null || isEmptyObject(commandResponse)) {
+    this.commandHandler(command, requestPayload)
+      .then(commandResponse => {
+        if (commandResponse == null || isEmptyObject(commandResponse)) {
+          responsePayload = {
+            hashId: this.chargingStation.stationInfo?.hashId,
+            status: ResponseStatus.SUCCESS
+          }
+        } else {
+          responsePayload = this.commandResponseToResponsePayload(
+            command,
+            requestPayload,
+            commandResponse
+          )
+        }
+      })
+      .catch(error => {
+        logger.error(
+          `${this.chargingStation.logPrefix()} ${moduleName}.requestHandler: Handle request error:`,
+          error
+        )
         responsePayload = {
           hashId: this.chargingStation.stationInfo?.hashId,
-          status: ResponseStatus.SUCCESS
-        }
-      } else {
-        responsePayload = this.commandResponseToResponsePayload(
+          status: ResponseStatus.FAILURE,
           command,
           requestPayload,
-          commandResponse
-        )
-      }
-    } catch (error) {
-      logger.error(
-        `${this.chargingStation.logPrefix()} ${moduleName}.requestHandler: Handle request error:`,
-        error
-      )
-      responsePayload = {
-        hashId: this.chargingStation.stationInfo?.hashId,
-        status: ResponseStatus.FAILURE,
-        command,
-        requestPayload,
+          // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+          commandResponse: commandResponse!,
+          errorMessage: (error as OCPPError).message,
+          errorStack: (error as OCPPError).stack,
+          errorDetails: (error as OCPPError).details
+        }
+      })
+      .finally(() => {
         // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-        commandResponse: commandResponse!,
-        errorMessage: (error as OCPPError).message,
-        errorStack: (error as OCPPError).stack,
-        errorDetails: (error as OCPPError).details
-      }
-    } finally {
-      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-      this.sendResponse([uuid, responsePayload!])
-    }
+        this.sendResponse([uuid, responsePayload!])
+      })
   }
 
   private messageErrorHandler (messageEvent: MessageEvent): void {
index a61dedd8edcfebfd6e0b26a17672ae7695f6d7d5..f934d418e6161600982b53d0ec7fb2a034682a6e 100644 (file)
@@ -332,11 +332,7 @@ export class OCPP16IncomingRequestService extends OCPPIncomingRequestService {
         )
       ]
     ])
-    this.validatePayload = this.validatePayload.bind(this) as (
-      chargingStation: ChargingStation,
-      commandName: OCPP16IncomingRequestCommand,
-      commandPayload: JsonType
-    ) => boolean
+    this.validatePayload = this.validatePayload.bind(this)
   }
 
   public async incomingRequestHandler<ReqType extends JsonType, ResType extends JsonType>(
index 297349bd5e8ad8840cd59e9f4ff11a6540eeb690..37a5b2ba2811c36610fa1b8002e89ab5c64b3081 100644 (file)
@@ -121,11 +121,7 @@ export class OCPP16RequestService extends OCPPRequestService {
         )
       ]
     ])
-    this.buildRequestPayload = this.buildRequestPayload.bind(this) as <Request extends JsonType>(
-      chargingStation: ChargingStation,
-      commandName: OCPP16RequestCommand,
-      commandParams?: JsonType
-    ) => Request
+    this.buildRequestPayload = this.buildRequestPayload.bind(this)
   }
 
   public async requestHandler<RequestType extends JsonType, ResponseType extends JsonType>(
index 5ceeb38a6bc01d2747bfd0308bb5cfd8d4d7aa4b..c47d2630fc41a2d948048e2f61648b33dc255f9a 100644 (file)
@@ -317,11 +317,7 @@ export class OCPP16ResponseService extends OCPPResponseService {
         )
       ]
     ])
-    this.validatePayload = this.validatePayload.bind(this) as (
-      chargingStation: ChargingStation,
-      commandName: OCPP16RequestCommand,
-      payload: JsonType
-    ) => boolean
+    this.validatePayload = this.validatePayload.bind(this)
   }
 
   public async responseHandler<ReqType extends JsonType, ResType extends JsonType>(
index 5480b5a388ec0d5c78c7eaffb4c3a83e2a915ab8..664189815103d2eb13580db72a568060f90dd924 100644 (file)
@@ -43,11 +43,7 @@ export class OCPP20IncomingRequestService extends OCPPIncomingRequestService {
         )
       ]
     ])
-    this.validatePayload = this.validatePayload.bind(this) as (
-      chargingStation: ChargingStation,
-      commandName: OCPP20IncomingRequestCommand,
-      commandPayload: JsonType
-    ) => boolean
+    this.validatePayload = this.validatePayload.bind(this)
   }
 
   public async incomingRequestHandler<ReqType extends JsonType, ResType extends JsonType>(
index 769064b99fc727096b8abc61cedc9129c6a698bd..e73b33ccb019cd92858fc5e15ad0aa59d1bd8b85 100644 (file)
@@ -57,11 +57,7 @@ export class OCPP20RequestService extends OCPPRequestService {
         )
       ]
     ])
-    this.buildRequestPayload = this.buildRequestPayload.bind(this) as <Request extends JsonType>(
-      chargingStation: ChargingStation,
-      commandName: OCPP20RequestCommand,
-      commandParams?: JsonType
-    ) => Request
+    this.buildRequestPayload = this.buildRequestPayload.bind(this)
   }
 
   public async requestHandler<RequestType extends JsonType, ResponseType extends JsonType>(
index ee4b201f20789b8a7f151a8381e4be74ae581d56..f35a8898eccec37284ea44b769af257ff8ccf300 100644 (file)
@@ -82,11 +82,7 @@ export class OCPP20ResponseService extends OCPPResponseService {
         )
       ]
     ])
-    this.validatePayload = this.validatePayload.bind(this) as (
-      chargingStation: ChargingStation,
-      commandName: OCPP20RequestCommand,
-      payload: JsonType
-    ) => boolean
+    this.validatePayload = this.validatePayload.bind(this)
   }
 
   public async responseHandler<ReqType extends JsonType, ResType extends JsonType>(
index 5eaddae90976cef25602583412ebd02e899909bb..4285e585ac7b3aaa5fa9b530c3109350b11558eb 100644 (file)
@@ -35,24 +35,8 @@ export abstract class OCPPIncomingRequestService {
     })
     ajvFormats(this.ajv)
     this.jsonValidateFunctions = new Map<IncomingRequestCommand, ValidateFunction<JsonType>>()
-    this.incomingRequestHandler = this.incomingRequestHandler.bind(this) as <
-      ReqType extends JsonType,
-      // eslint-disable-next-line @typescript-eslint/no-unused-vars
-      ResType extends JsonType
-    >(
-      chargingStation: ChargingStation,
-      messageId: string,
-      commandName: IncomingRequestCommand,
-      commandPayload: ReqType
-    ) => Promise<void>
-    this.validateIncomingRequestPayload = this.validateIncomingRequestPayload.bind(this) as <
-      T extends JsonType
-    >(
-      chargingStation: ChargingStation,
-      commandName: IncomingRequestCommand,
-      schema: JSONSchemaType<T>,
-      payload: T
-    ) => boolean
+    this.incomingRequestHandler = this.incomingRequestHandler.bind(this)
+    this.validateIncomingRequestPayload = this.validateIncomingRequestPayload.bind(this)
   }
 
   public static getInstance<T extends OCPPIncomingRequestService>(this: new () => T): T {
index e03feba9650d2d4cb8789a77bc9e17cb2a37f74d..a56f1ac6bb5b6158c9b3d70dfacc47cb6cb93c39 100644 (file)
@@ -59,62 +59,15 @@ export abstract class OCPPRequestService {
     ajvFormats(this.ajv)
     this.jsonValidateFunctions = new Map<RequestCommand, ValidateFunction<JsonType>>()
     this.ocppResponseService = ocppResponseService
-    this.requestHandler = this.requestHandler.bind(this) as <
-      // eslint-disable-next-line @typescript-eslint/no-unused-vars
-      ReqType extends JsonType,
-      ResType extends JsonType
-    >(
-      chargingStation: ChargingStation,
-      commandName: RequestCommand,
-      commandParams?: JsonType,
-      params?: RequestParams
-    ) => Promise<ResType>
-    this.sendMessage = this.sendMessage.bind(this) as (
-      chargingStation: ChargingStation,
-      messageId: string,
-      messagePayload: JsonType,
-      commandName: RequestCommand,
-      params?: RequestParams
-    ) => Promise<ResponseType>
-    this.sendResponse = this.sendResponse.bind(this) as (
-      chargingStation: ChargingStation,
-      messageId: string,
-      messagePayload: JsonType,
-      commandName: IncomingRequestCommand
-    ) => Promise<ResponseType>
-    this.sendError = this.sendError.bind(this) as (
-      chargingStation: ChargingStation,
-      messageId: string,
-      ocppError: OCPPError,
-      commandName: RequestCommand | IncomingRequestCommand
-    ) => Promise<ResponseType>
-    this.internalSendMessage = this.internalSendMessage.bind(this) as (
-      chargingStation: ChargingStation,
-      messageId: string,
-      messagePayload: JsonType | OCPPError,
-      messageType: MessageType,
-      commandName: RequestCommand | IncomingRequestCommand,
-      params?: RequestParams
-    ) => Promise<ResponseType>
-    this.buildMessageToSend = this.buildMessageToSend.bind(this) as (
-      chargingStation: ChargingStation,
-      messageId: string,
-      messagePayload: JsonType | OCPPError,
-      messageType: MessageType,
-      commandName: RequestCommand | IncomingRequestCommand
-    ) => string
-    this.validateRequestPayload = this.validateRequestPayload.bind(this) as <T extends JsonType>(
-      chargingStation: ChargingStation,
-      commandName: RequestCommand | IncomingRequestCommand,
-      payload: T
-    ) => boolean
-    this.validateIncomingRequestResponsePayload = this.validateIncomingRequestResponsePayload.bind(
-      this
-    ) as <T extends JsonType>(
-      chargingStation: ChargingStation,
-      commandName: RequestCommand | IncomingRequestCommand,
-      payload: T
-    ) => boolean
+    this.requestHandler = this.requestHandler.bind(this)
+    this.sendMessage = this.sendMessage.bind(this)
+    this.sendResponse = this.sendResponse.bind(this)
+    this.sendError = this.sendError.bind(this)
+    this.internalSendMessage = this.internalSendMessage.bind(this)
+    this.buildMessageToSend = this.buildMessageToSend.bind(this)
+    this.validateRequestPayload = this.validateRequestPayload.bind(this)
+    this.validateIncomingRequestResponsePayload =
+      this.validateIncomingRequestResponsePayload.bind(this)
   }
 
   public static getInstance<T extends OCPPRequestService>(
index 20cfab6e967a6ee2e9f3278519124ff5a9b25532..e47450890076f3b200420bd014718e2c7b88f9af 100644 (file)
@@ -47,21 +47,8 @@ export abstract class OCPPResponseService {
     IncomingRequestCommand,
     ValidateFunction<JsonType>
     >()
-    this.responseHandler = this.responseHandler.bind(this) as <
-      ReqType extends JsonType,
-      ResType extends JsonType
-    >(
-      chargingStation: ChargingStation,
-      commandName: RequestCommand,
-      payload: ResType,
-      requestPayload: ReqType
-    ) => Promise<void>
-    this.validateResponsePayload = this.validateResponsePayload.bind(this) as <T extends JsonType>(
-      chargingStation: ChargingStation,
-      commandName: RequestCommand,
-      schema: JSONSchemaType<T>,
-      payload: T
-    ) => boolean
+    this.responseHandler = this.responseHandler.bind(this)
+    this.validateResponsePayload = this.validateResponsePayload.bind(this)
   }
 
   public static getInstance<T extends OCPPResponseService>(this: new () => T): T {
index eb3550830682f45cff76aff8559df71b34e855f5..7c102195413aed23e4a68e5ee28abf1657a9fcf8 100644 (file)
@@ -1,4 +1,4 @@
-import type { IncomingMessage, RequestListener, ServerResponse } from 'node:http'
+import type { IncomingMessage, ServerResponse } from 'node:http'
 
 import { StatusCodes } from 'http-status-codes'
 
@@ -33,7 +33,7 @@ export class UIHttpServer extends AbstractUIServer {
   }
 
   public start (): void {
-    this.httpServer.on('request', this.requestListener.bind(this) as RequestListener)
+    this.httpServer.on('request', this.requestListener.bind(this))
     this.startHttpServer()
   }