build(deps-dev): apply updates
[e-mobility-charging-stations-simulator.git] / src / worker / WorkerFactory.ts
CommitLineData
66a7748d 1import { isMainThread } from 'node:worker_threads'
b8da29bc 2
56f94590
JB
3import { mergeDeepRight } from 'rambda'
4
66a7748d
JB
5import type { WorkerAbstract } from './WorkerAbstract.js'
6import { DEFAULT_WORKER_OPTIONS } from './WorkerConstants.js'
7import { WorkerDynamicPool } from './WorkerDynamicPool.js'
8import { WorkerFixedPool } from './WorkerFixedPool.js'
9import { WorkerSet } from './WorkerSet.js'
10import { type WorkerData, type WorkerOptions, WorkerProcessType } from './WorkerTypes.js'
6013bc53 11
66a7748d 12// eslint-disable-next-line @typescript-eslint/no-extraneous-class
268a74bb 13export class WorkerFactory {
66a7748d 14 private constructor () {
6c3cfef8
JB
15 // This is intentional
16 }
8df3f0a9 17
e7aeea18
JB
18 public static getWorkerImplementation<T extends WorkerData>(
19 workerScript: string,
20 workerProcessType: WorkerProcessType,
66a7748d 21 workerOptions?: WorkerOptions
6d2b7d01 22 ): WorkerAbstract<T> | undefined {
ded13d97 23 if (!isMainThread) {
66a7748d 24 throw new Error('Cannot get a worker implementation outside the main thread')
ded13d97 25 }
56f94590 26 workerOptions = mergeDeepRight<WorkerOptions>(DEFAULT_WORKER_OPTIONS, workerOptions ?? {})
66a7748d 27 let workerImplementation: WorkerAbstract<T>
535aaa27 28 switch (workerProcessType) {
721646e9 29 case WorkerProcessType.workerSet:
66a7748d
JB
30 workerImplementation = new WorkerSet(workerScript, workerOptions)
31 break
1d8f226b 32 case WorkerProcessType.fixedPool:
66a7748d
JB
33 workerImplementation = new WorkerFixedPool(workerScript, workerOptions)
34 break
721646e9 35 case WorkerProcessType.dynamicPool:
66a7748d
JB
36 workerImplementation = new WorkerDynamicPool(workerScript, workerOptions)
37 break
fb226c9b 38 default:
3fa0f0ed 39 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
66a7748d 40 throw new Error(`Worker implementation type '${workerProcessType}' not found`)
6013bc53 41 }
66a7748d 42 return workerImplementation
6013bc53
JB
43 }
44}