fix: fix possible null exception with worker_threads pools
[poolifier.git] / src / worker / thread-worker.ts
index 8d30ef21a8874dcfb6802e2436a7d6033a4fa8ec..e133430f5029813aaac582c1a7156f053293d75f 100644 (file)
@@ -30,7 +30,7 @@ export class ThreadWorker<
   /**
    * Message port used to communicate with the main worker.
    */
-  private port!: MessagePort
+  private port?: MessagePort
   /**
    * Constructs a new poolifier thread worker.
    *
@@ -41,13 +41,7 @@ export class ThreadWorker<
     taskFunctions: TaskFunction<Data, Response> | TaskFunctions<Data, Response>,
     opts: WorkerOptions = {}
   ) {
-    super(
-      'worker-thread-pool:poolifier',
-      isMainThread,
-      parentPort as MessagePort,
-      taskFunctions,
-      opts
-    )
+    super(isMainThread, parentPort as MessagePort, taskFunctions, opts)
   }
 
   /** @inheritDoc */
@@ -62,14 +56,12 @@ export class ThreadWorker<
         this.port.on('message', this.messageListener.bind(this))
         this.sendToMainWorker({
           ready: true,
-          taskFunctions: this.listTaskFunctions(),
-          workerId: this.id
+          taskFunctionNames: this.listTaskFunctionNames()
         })
       } catch {
         this.sendToMainWorker({
           ready: false,
-          taskFunctions: this.listTaskFunctions(),
-          workerId: this.id
+          taskFunctionNames: this.listTaskFunctionNames()
         })
       }
     }
@@ -88,12 +80,17 @@ export class ThreadWorker<
   }
 
   /** @inheritDoc */
-  protected sendToMainWorker (message: MessageValue<Response>): void {
-    this.port.postMessage(message)
+  protected readonly sendToMainWorker = (
+    message: MessageValue<Response>
+  ): void => {
+    this.port?.postMessage({ ...message, workerId: this.id })
   }
 
-  /** @inheritDoc */
-  protected handleError (e: Error | string): string {
-    return e as string
+  /**
+   * @inheritDoc
+   * @override
+   */
+  protected handleError (error: Error | string): string {
+    return error as string
   }
 }