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