From 6b57eb9a3fccc8e29028b00a3a1f33544852760f Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Thu, 1 Jun 2023 04:43:07 +0200 Subject: [PATCH] refactor: encapsulate worker in an object MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- src/charging-station/ChargingStationWorker.ts | 46 +++++++++---------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/src/charging-station/ChargingStationWorker.ts b/src/charging-station/ChargingStationWorker.ts index 19dd6f8d..3703de9c 100644 --- a/src/charging-station/ChargingStationWorker.ts +++ b/src/charging-station/ChargingStationWorker.ts @@ -1,7 +1,7 @@ // Partial Copyright Jerome Benoit. 2021-2023. All Rights Reserved. import { AsyncResource } from 'node:async_hooks'; -import { parentPort, workerData } from 'node:worker_threads'; +import { parentPort } from 'node:worker_threads'; import { ThreadWorker } from 'poolifier'; @@ -19,6 +19,27 @@ const startChargingStation = (data: ChargingStationWorkerData): void => { new ChargingStation(data.index, data.templateFile).start(); }; +class ChargingStationWorker extends AsyncResource { + constructor() { + super('ChargingStationWorker'); + // Add message listener to create and start charging station from the main thread + parentPort?.on('message', (message: WorkerMessage) => { + if (message.id === WorkerMessageEvents.startWorkerElement) { + this.run(message.data); + } + }); + } + + private run(data: ChargingStationWorkerData): void { + this.runInAsyncScope( + startChargingStation.bind(this) as (data: ChargingStationWorkerData) => void, + this, + data + ); + } +} + +export let chargingStationWorker: ChargingStationWorker; // Conditionally export ThreadWorker instance for pool usage export let threadWorker: ThreadWorker; if (Configuration.workerPoolInUse()) { @@ -26,26 +47,5 @@ if (Configuration.workerPoolInUse()) { maxInactiveTime: WorkerConstants.POOL_MAX_INACTIVE_TIME, }); } else { - class ChargingStationWorker extends AsyncResource { - constructor() { - super('ChargingStationWorker'); - } - - public run(data: ChargingStationWorkerData): void { - this.runInAsyncScope( - startChargingStation.bind(this) as (data: ChargingStationWorkerData) => void, - this, - data - ); - } - } - // Add message listener to create and start charging station from the main thread - parentPort?.on('message', (message: WorkerMessage) => { - if (message.id === WorkerMessageEvents.startWorkerElement) { - new ChargingStationWorker().run(message.data); - } - }); - if (workerData !== undefined) { - new ChargingStationWorker().run(workerData as ChargingStationWorkerData); - } + chargingStationWorker = new ChargingStationWorker(); } -- 2.34.1