feat: ensure charging station add op return its station info
[e-mobility-charging-stations-simulator.git] / src / charging-station / ChargingStationWorker.ts
CommitLineData
a19b897d 1// Partial Copyright Jerome Benoit. 2021-2024. All Rights Reserved.
c8eeb62b 2
66a7748d 3import { parentPort } from 'node:worker_threads'
8114d10e 4
66a7748d 5import { ThreadWorker } from 'poolifier'
8114d10e 6
66a7748d 7import { BaseError } from '../exception/index.js'
244c1396 8import type {
3b09e788 9 ChargingStationInfo,
244c1396
JB
10 ChargingStationWorkerData,
11 ChargingStationWorkerEventError,
12 ChargingStationWorkerMessage
13} from '../types/index.js'
3b09e788 14import { Configuration } from '../utils/index.js'
66a7748d 15import { type WorkerMessage, WorkerMessageEvents } from '../worker/index.js'
4c3f6c20 16import { ChargingStation } from './ChargingStation.js'
11353865 17
244c1396 18export let chargingStationWorker: object
aa7d6d95 19if (Configuration.workerPoolInUse()) {
3b09e788
JB
20 chargingStationWorker = new ThreadWorker<
21 ChargingStationWorkerData,
22 ChargingStationInfo | undefined
23 >((data?: ChargingStationWorkerData): ChargingStationInfo | undefined => {
24 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion, no-new
25 return new ChargingStation(data!.index, data!.templateFile, data!.options).stationInfo
26 })
74bbc59b 27} else {
244c1396
JB
28 // eslint-disable-next-line @typescript-eslint/no-extraneous-class
29 class ChargingStationWorker<Data extends ChargingStationWorkerData> {
30 constructor () {
31 parentPort?.on('message', (message: WorkerMessage<Data>) => {
32 switch (message.event) {
33 case WorkerMessageEvents.addWorkerElement:
34 try {
35 const chargingStation = new ChargingStation(
36 message.data.index,
71ac2bd7
JB
37 message.data.templateFile,
38 message.data.options
244c1396 39 )
244c1396
JB
40 parentPort?.postMessage({
41 event: WorkerMessageEvents.addedWorkerElement,
3b09e788
JB
42 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
43 data: chargingStation.stationInfo!
44 } satisfies ChargingStationWorkerMessage<ChargingStationInfo>)
244c1396
JB
45 } catch (error) {
46 parentPort?.postMessage({
47 event: WorkerMessageEvents.workerElementError,
48 data: {
3b09e788 49 event: message.event,
244c1396
JB
50 name: (error as Error).name,
51 message: (error as Error).message,
52 stack: (error as Error).stack
53 }
54 } satisfies ChargingStationWorkerMessage<ChargingStationWorkerEventError>)
55 }
56 break
57 default:
58 throw new BaseError(
59 `Unknown worker event: '${message.event}' received with data: '${JSON.stringify(
60 message.data,
61 undefined,
62 2
63 )}'`
64 )
65 }
66 })
67 }
68 }
66a7748d 69 chargingStationWorker = new ChargingStationWorker<ChargingStationWorkerData>()
3d2ff9e4 70}