]> Piment Noir Git Repositories - e-mobility-charging-stations-simulator.git/commitdiff
refactor: use getErrorMessage helper and extract auth cache constant
authorJérôme Benoit <jerome.benoit@sap.com>
Fri, 3 Apr 2026 15:42:38 +0000 (17:42 +0200)
committerJérôme Benoit <jerome.benoit@sap.com>
Fri, 3 Apr 2026 15:42:38 +0000 (17:42 +0200)
Replace 7 instanceof Error ternary patterns with getErrorMessage()
for consistent error message extraction. Extract hardcoded
maxEntries 1000 to Constants.DEFAULT_AUTH_CACHE_MAX_ENTRIES
across InMemoryAuthCache, AuthComponentFactory, and
OCPPAuthServiceImpl.

src/charging-station/ocpp/2.0/OCPP20CertificateManager.ts
src/charging-station/ocpp/2.0/OCPP20RequestService.ts
src/charging-station/ocpp/auth/adapters/OCPP16AuthAdapter.ts
src/charging-station/ocpp/auth/adapters/OCPP20AuthAdapter.ts
src/charging-station/ocpp/auth/cache/InMemoryAuthCache.ts
src/charging-station/ocpp/auth/factories/AuthComponentFactory.ts
src/charging-station/ocpp/auth/services/OCPPAuthServiceImpl.ts
src/charging-station/ui-server/UIMCPServer.ts
src/performance/PerformanceStatistics.ts
src/utils/Constants.ts

index 9468f1b6edce3862700323110512e2032f191215..ea79c572a353ff47bbca875de303db134cd9ea3d 100644 (file)
@@ -486,7 +486,7 @@ export class OCPP20CertificateManager {
       return { valid: true }
     } catch (error) {
       return {
-        reason: `Certificate parsing failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
+        reason: `Certificate parsing failed: ${getErrorMessage(error)}`,
         valid: false,
       }
     }
index 980aecb0e2b3eb8f96e7ed6a1ba5b3e350e737dd..2e456a0b364824d363c610e033894b97900d208b 100644 (file)
@@ -19,7 +19,7 @@ import {
   OCPPVersion,
   type RequestParams,
 } from '../../../types/index.js'
-import { generateUUID, logger } from '../../../utils/index.js'
+import { generateUUID, getErrorMessage, logger } from '../../../utils/index.js'
 import { OCPPRequestService } from '../OCPPRequestService.js'
 import { createPayloadValidatorMap, isRequestCommandSupported } from '../OCPPServiceUtils.js'
 import { generatePkcs10Csr } from './Asn1DerUtils.js'
@@ -179,7 +179,7 @@ export class OCPP20RequestService extends OCPPRequestService {
 
           csr = generatePkcs10Csr(stationId, orgName)
         } catch (error) {
-          const errorMsg = `Failed to generate CSR: ${error instanceof Error ? error.message : 'Unknown error'}`
+          const errorMsg = `Failed to generate CSR: ${getErrorMessage(error)}`
           logger.error(
             `${chargingStation.logPrefix()} ${moduleName}.buildRequestPayload: ${errorMsg}`
           )
index fb90d924c1b2f52ff5349d5d7292d3652840353e..17d5d38600b0987acbbf3d4fcce0ede0aef05ed1 100644 (file)
@@ -16,7 +16,7 @@ import {
   RequestCommand,
   StandardParametersKey,
 } from '../../../../types/index.js'
-import { convertToBoolean, logger, truncateId } from '../../../../utils/index.js'
+import { convertToBoolean, getErrorMessage, logger, truncateId } from '../../../../utils/index.js'
 import {
   AuthContext,
   AuthenticationMethod,
@@ -105,7 +105,7 @@ export class OCPP16AuthAdapter implements OCPPAuthAdapter<string> {
       return {
         additionalInfo: {
           connectorId,
-          error: error instanceof Error ? error.message : 'Unknown error',
+          error: getErrorMessage(error),
           transactionId,
         },
         isOffline: false,
index 937d3fcd0674c00d2b2fb9a891c65d31a7102e9b..8463478911fb0f80c50900ab69a18f17eb2aae41 100644 (file)
@@ -23,7 +23,7 @@ import {
   OCPP20RequiredVariableName,
   OCPPVersion,
 } from '../../../../types/index.js'
-import { logger, truncateId } from '../../../../utils/index.js'
+import { getErrorMessage, logger, truncateId } from '../../../../utils/index.js'
 import {
   AuthContext,
   AuthenticationMethod,
@@ -142,7 +142,7 @@ export class OCPP20AuthAdapter implements OCPPAuthAdapter<OCPP20IdTokenType> {
       return {
         additionalInfo: {
           connectorId,
-          error: error instanceof Error ? error.message : 'Unknown error',
+          error: getErrorMessage(error),
           transactionId,
         },
         isOffline: false,
index e46c10d2bd522a72536380fbbb4c8fc8c8a1f066..4b46aac910a682c263ab941fc5a2c135f8ae3d29 100644 (file)
@@ -3,7 +3,7 @@ import { secondsToMilliseconds } from 'date-fns'
 import type { AuthCache, CacheStats } from '../interfaces/OCPPAuthService.js'
 import type { AuthorizationResult } from '../types/AuthTypes.js'
 
-import { logger, truncateId } from '../../../../utils/index.js'
+import { Constants, logger, truncateId } from '../../../../utils/index.js'
 import { AuthorizationStatus } from '../types/AuthTypes.js'
 
 const moduleName = 'InMemoryAuthCache'
@@ -108,7 +108,7 @@ export class InMemoryAuthCache implements AuthCache {
    * @param options.cleanupIntervalSeconds - Periodic cleanup interval in seconds (default: 300, 0 to disable)
    * @param options.defaultTtl - Default TTL in seconds (default: 3600)
    * @param options.maxAbsoluteLifetimeMs - Absolute lifetime cap in milliseconds (default: 86400000)
-   * @param options.maxEntries - Maximum number of cache entries (default: 1000)
+   * @param options.maxEntries - Maximum number of cache entries (default: Constants.DEFAULT_AUTH_CACHE_MAX_ENTRIES)
    * @param options.rateLimit - Rate limiting configuration
    * @param options.rateLimit.enabled - Enable rate limiting (default: false)
    * @param options.rateLimit.maxRequests - Max requests per window (default: 10)
@@ -124,7 +124,7 @@ export class InMemoryAuthCache implements AuthCache {
     this.defaultTtl = options?.defaultTtl ?? 3600 // 1 hour default
     this.maxAbsoluteLifetimeMs =
       options?.maxAbsoluteLifetimeMs ?? InMemoryAuthCache.DEFAULT_MAX_ABSOLUTE_LIFETIME_MS
-    this.maxEntries = Math.max(1, options?.maxEntries ?? 1000)
+    this.maxEntries = Math.max(1, options?.maxEntries ?? Constants.DEFAULT_AUTH_CACHE_MAX_ENTRIES)
     this.rateLimit = {
       enabled: options?.rateLimit?.enabled ?? false,
       maxRequests: options?.rateLimit?.maxRequests ?? 10, // 10 requests per window
index a92421512e2946dc8b366655e96bc69e0d5d7b7d..fa938a360b9a4cc6eab299032c67c591cf0788f4 100644 (file)
@@ -9,6 +9,7 @@ import type { AuthConfiguration } from '../types/AuthTypes.js'
 
 import { OCPPError } from '../../../../exception/index.js'
 import { ErrorType, OCPPVersion } from '../../../../types/index.js'
+import { Constants } from '../../../../utils/index.js'
 import { OCPP16AuthAdapter } from '../adapters/OCPP16AuthAdapter.js'
 import { OCPP20AuthAdapter } from '../adapters/OCPP20AuthAdapter.js'
 import { InMemoryAuthCache } from '../cache/InMemoryAuthCache.js'
@@ -70,7 +71,7 @@ export class AuthComponentFactory {
   static createAuthCache (config: AuthConfiguration): AuthCache {
     return new InMemoryAuthCache({
       defaultTtl: config.authorizationCacheLifetime ?? 3600,
-      maxEntries: config.maxCacheEntries ?? 1000,
+      maxEntries: config.maxCacheEntries ?? Constants.DEFAULT_AUTH_CACHE_MAX_ENTRIES,
     })
   }
 
index e195826507f3f80fd2d84ccaa99d1a7bbd67cf1d..f320921bb2d5773fac2f3a279dcf5d13779749d3 100644 (file)
@@ -5,6 +5,7 @@ import type { OCPPAuthAdapter } from '../interfaces/OCPPAuthService.js'
 import { OCPPError } from '../../../../exception/index.js'
 import { ErrorType, OCPPVersion } from '../../../../types/index.js'
 import {
+  Constants,
   convertToDate,
   ensureError,
   getErrorMessage,
@@ -592,7 +593,7 @@ export class OCPPAuthServiceImpl implements OCPPAuthService {
       certificateValidationStrict: false,
       localAuthListEnabled: true,
       localPreAuthorize: false,
-      maxCacheEntries: 1000,
+      maxCacheEntries: Constants.DEFAULT_AUTH_CACHE_MAX_ENTRIES,
       ocppVersion: this.chargingStation.stationInfo?.ocppVersion,
       offlineAuthorizationEnabled: true,
       remoteAuthorization: true,
index a7b384bd964712067af3e9dafc53d3ec07678e6b..38854dcd1aebaffbe573055b271bd3e6d8e27d9a 100644 (file)
@@ -22,7 +22,7 @@ import {
   type UIServerConfiguration,
   type UUIDv4,
 } from '../../types/index.js'
-import { generateUUID, logger } from '../../utils/index.js'
+import { generateUUID, getErrorMessage, logger } from '../../utils/index.js'
 import { AbstractUIServer } from './AbstractUIServer.js'
 import {
   mcpToolSchemas,
@@ -278,8 +278,7 @@ export class UIMCPServer extends AbstractUIServer {
     } catch (error: unknown) {
       logger.error(`${this.logPrefix(moduleName, 'handleMcpRequest')} MCP transport error:`, error)
       const isBadRequest =
-        error instanceof SyntaxError ||
-        (error instanceof Error && error.message.includes('Payload too large'))
+        error instanceof SyntaxError || getErrorMessage(error).includes('Payload too large')
       this.sendErrorResponse(res, isBadRequest ? 400 : 500)
     }
   }
@@ -404,11 +403,7 @@ export class UIMCPServer extends AbstractUIServer {
             clearTimeout(pending.timeout)
             this.pendingMcpRequests.delete(uuid)
           }
-          resolve(
-            UIMCPServer.createToolErrorResponse(
-              error instanceof Error ? error.message : String(error)
-            )
-          )
+          resolve(UIMCPServer.createToolErrorResponse(getErrorMessage(error)))
         })
     })
   }
index 07439a2978c3a57ad8860f58b85da7bd4ecf6a9f..269fa58cb7833acb2fce315663adf0b177e87605 100644 (file)
@@ -28,6 +28,7 @@ import {
   extractTimeSeriesValues,
   formatDurationSeconds,
   generateUUID,
+  getErrorMessage,
   JSONStringify,
   logger,
   logPrefix,
@@ -82,7 +83,7 @@ export class PerformanceStatistics {
     try {
       performance.measure(name, markId)
     } catch (error) {
-      if (error instanceof Error && error.message.includes('performance mark has not been set')) {
+      if (getErrorMessage(error).includes('performance mark has not been set')) {
         /* Ignore */
       } else {
         throw error
index ed6e9a4953dbddfbf1f25d3a7f2737d25e986e4f..306ebcb5cff5530ae8d04fd6259d6897d11e9593 100644 (file)
@@ -22,6 +22,8 @@ export class Constants {
 
   static readonly DEFAULT_ATG_WAIT_TIME = 1000 // Ms
 
+  static readonly DEFAULT_AUTH_CACHE_MAX_ENTRIES = 1000
+
   static readonly DEFAULT_BOOT_NOTIFICATION_INTERVAL = 60000 // Ms
 
   static readonly DEFAULT_CIRCULAR_BUFFER_CAPACITY = 386