perf: 'await' on UI request handlers only when necessary
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / ui-services / AbstractUIService.ts
index 499e96990949e9c89a614e4411b6cbc576a75c43..416d660d7d5f4c6ead5a5f003c528f13d69b0c9e 100644 (file)
@@ -12,7 +12,7 @@ import {
   type ResponsePayload,
   ResponseStatus
 } from '../../../types/index.js'
-import { isNotEmptyArray, isNullOrUndefined, logger } from '../../../utils/index.js'
+import { isAsyncFunction, isNotEmptyArray, logger } from '../../../utils/index.js'
 import { Bootstrap } from '../../Bootstrap.js'
 import { UIServiceWorkerBroadcastChannel } from '../../broadcast-channel/UIServiceWorkerBroadcastChannel.js'
 import type { AbstractUIServer } from '../AbstractUIServer.js'
@@ -93,7 +93,18 @@ export abstract class AbstractUIService {
 
       // Call the request handler to build the response payload
       // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-      responsePayload = await this.requestHandlers.get(command)!(messageId, command, requestPayload)
+      const requestHandler = this.requestHandlers.get(command)!
+      if (isAsyncFunction(requestHandler)) {
+        responsePayload = await requestHandler(messageId, command, requestPayload)
+      } else {
+        responsePayload = (
+          requestHandler as (
+            uuid?: string,
+            procedureName?: ProcedureName,
+            payload?: RequestPayload
+          ) => undefined | ResponsePayload
+        )(messageId, command, requestPayload)
+      }
     } catch (error) {
       // Log
       logger.error(`${this.logPrefix(moduleName, 'requestHandler')} Handle request error:`, error)
@@ -108,9 +119,9 @@ export abstract class AbstractUIService {
         errorDetails: (error as OCPPError).details
       }
     }
-    if (!isNullOrUndefined(responsePayload)) {
+    if (responsePayload != null) {
       // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
-      return this.uiServer.buildProtocolResponse(messageId!, responsePayload!)
+      return this.uiServer.buildProtocolResponse(messageId!, responsePayload)
     }
   }
 
@@ -163,8 +174,8 @@ export abstract class AbstractUIService {
   ): void {
     if (isNotEmptyArray(payload.hashIds)) {
       payload.hashIds = payload.hashIds
-        ?.map((hashId) => {
-          if (hashId != null && this.uiServer.chargingStations.has(hashId)) {
+        .map(hashId => {
+          if (this.uiServer.chargingStations.has(hashId)) {
             return hashId
           }
           logger.warn(
@@ -175,7 +186,7 @@ export abstract class AbstractUIService {
           )
           return undefined
         })
-        ?.filter((hashId) => !isNullOrUndefined(hashId)) as string[]
+        .filter(hashId => hashId != null) as string[]
     } else {
       delete payload.hashIds
     }