- this.mainWorker?.on('message', (value: MessageValue<Data, MainWorker>) => {
- if (value?.data && value.id) {
- // Here you will receive messages
- if (this.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.interval) clearInterval(this.interval)
- this.emitDestroy()
+ this.mainWorker?.on(
+ 'message',
+ (message: MessageValue<Data, MainWorker>) => {
+ this.messageListener(message, fn)
+ }
+ )
+ }
+
+ 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: WorkerFunction<Data, 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'
+ )
+ }
+ }
+
+ /**
+ * 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: WorkerFunction<Data, 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)