Convert function to arrow function in UT
[poolifier.git] / src / worker / abstract-worker.ts
index 3a8414d84ff7aba6d8524d908a3b53094f583fa4..b49ede8b0802f1baf39230b087f9b6b99050e8e3 100644 (file)
@@ -21,10 +21,6 @@ export abstract class AbstractWorker<
   Data = unknown,
   Response = unknown
 > extends AsyncResource {
-  /**
-   * Options for the worker.
-   */
-  public readonly opts: WorkerOptions
   /**
    * Timestamp of the last task processed by this worker.
    */
@@ -33,7 +29,10 @@ export abstract class AbstractWorker<
    * Handler Id of the `aliveInterval` worker alive check.
    */
   protected readonly aliveInterval?: NodeJS.Timeout
-
+  /**
+   * Options for the worker.
+   */
+  public readonly opts: WorkerOptions
   /**
    * Constructs a new poolifier worker.
    *
@@ -75,25 +74,32 @@ export abstract class AbstractWorker<
     }
 
     this.mainWorker?.on('message', (value: MessageValue<Data, MainWorker>) => {
-      if (value?.data && value.id) {
-        // Here you will receive messages
-        if (this.opts.async) {
-          this.runInAsyncScope(this.runAsync.bind(this), this, fn, value)
-        } else {
-          this.runInAsyncScope(this.run.bind(this), this, fn, value)
-        }
-      } else if (value.parent) {
-        // Save a reference of the main worker to communicate with it
-        // This will be received once
-        this.mainWorker = value.parent
-      } else if (value.kill) {
-        // Here is time to kill this worker, just clearing the interval
-        if (this.aliveInterval) clearInterval(this.aliveInterval)
-        this.emitDestroy()
-      }
+      this.messageListener(value, fn)
     })
   }
 
+  protected messageListener (
+    value: MessageValue<Data, MainWorker>,
+    fn: (data: Data) => Response
+  ): void {
+    if (value.data !== undefined && value.id !== undefined) {
+      // Here you will receive messages
+      if (this.opts.async) {
+        this.runInAsyncScope(this.runAsync.bind(this), this, fn, value)
+      } else {
+        this.runInAsyncScope(this.run.bind(this), this, fn, value)
+      }
+    } else if (value.parent !== undefined) {
+      // Save a reference of the main worker to communicate with it
+      // This will be received once
+      this.mainWorker = value.parent
+    } else if (value.kill !== undefined) {
+      // Here is time to kill this worker, just clearing the interval
+      if (this.aliveInterval) clearInterval(this.aliveInterval)
+      this.emitDestroy()
+    }
+  }
+
   private checkWorkerOptions (opts: WorkerOptions) {
     this.opts.killBehavior = opts.killBehavior ?? DEFAULT_KILL_BEHAVIOR
     this.opts.maxInactiveTime =
@@ -191,7 +197,7 @@ export abstract class AbstractWorker<
         return null
       })
       .catch(e => {
-        const err = this.handleError(e)
+        const err = this.handleError(e as Error)
         this.sendToMainWorker({ error: err, id: value.id })
       })
       .finally(() => {