+
+ this.mainWorker?.on(
+ 'message',
+ (message: MessageValue<Data, MainWorker>) => {
+ this.messageListener(message, fn)
+ }
+ )
+ }
+
+ /**
+ * Worker message listener.
+ *
+ * @param message - Message received.
+ * @param fn - Function processed by the worker when the pool's `execution` function is invoked.
+ */
+ protected messageListener (
+ message: MessageValue<Data, MainWorker>,
+ fn: (data: Data) => Response | Promise<Response>
+ ): void {
+ if (message.id != null && message.data != null) {
+ // Task message received
+ if (this.opts.async === true) {
+ this.runInAsyncScope(this.runAsync.bind(this), this, fn, message)
+ } else {
+ this.runInAsyncScope(this.run.bind(this), this, fn, message)
+ }
+ } else if (message.parent != null) {
+ // Main worker reference message received
+ this.mainWorker = message.parent
+ } else if (message.kill != null) {
+ // Kill message received
+ this.aliveInterval != null && clearInterval(this.aliveInterval)
+ this.emitDestroy()
+ }
+ }
+
+ private checkWorkerOptions (opts: WorkerOptions): void {
+ this.opts.killBehavior = opts.killBehavior ?? DEFAULT_KILL_BEHAVIOR
+ this.opts.maxInactiveTime =
+ opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME
+ this.opts.async = opts.async ?? false
+ }
+
+ /**
+ * Checks if the `fn` parameter is passed to the constructor.
+ *
+ * @param fn - The function that should be defined.
+ */
+ private checkFunctionInput (
+ fn: (data: Data) => Response | Promise<Response>
+ ): void {
+ if (fn == null) throw new Error('fn parameter is mandatory')
+ if (typeof fn !== 'function') {
+ throw new TypeError('fn parameter is not a function')
+ }
+ if (fn.constructor.name === 'AsyncFunction' && this.opts.async === false) {
+ throw new Error(
+ 'fn parameter is an async function, please set the async option to true'
+ )
+ }