From: Jérôme Benoit Date: Thu, 4 May 2023 20:54:39 +0000 (+0200) Subject: refactor: add helper to get worker function X-Git-Tag: v2.4.12~15^2~10 X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=ec8fd33166d2c3d5632353d21e737e8443519dc1;p=poolifier.git refactor: add helper to get worker function Signed-off-by: Jérôme Benoit --- diff --git a/src/worker/abstract-worker.ts b/src/worker/abstract-worker.ts index 788c5dfa..0c6d1ac3 100644 --- a/src/worker/abstract-worker.ts +++ b/src/worker/abstract-worker.ts @@ -12,6 +12,7 @@ import { EMPTY_FUNCTION } from '../utils' import type { KillBehavior, WorkerOptions } from './worker-options' import { KillBehaviors } from './worker-options' +const DEFAULT_FUNCTION_NAME = 'default' const DEFAULT_MAX_INACTIVE_TIME = 60000 const DEFAULT_KILL_BEHAVIOR: KillBehavior = KillBehaviors.SOFT @@ -104,7 +105,9 @@ export abstract class AbstractWorker< | WorkerFunction | TaskFunctions ): void { - if (taskFunctions == null) { throw new Error('taskFunctions parameter is mandatory') } + if (taskFunctions == null) { + throw new Error('taskFunctions parameter is mandatory') + } if ( typeof taskFunctions !== 'function' && typeof taskFunctions !== 'object' @@ -129,7 +132,7 @@ export abstract class AbstractWorker< this.taskFunctions.set(name, fn.bind(this)) } } else { - this.taskFunctions.set('default', taskFunctions.bind(this)) + this.taskFunctions.set(DEFAULT_FUNCTION_NAME, taskFunctions.bind(this)) } } @@ -140,12 +143,7 @@ export abstract class AbstractWorker< */ protected messageListener (message: MessageValue): void { if (message.id != null && message.data != null) { - let fn: WorkerFunction | undefined - if (message.name == null) { - fn = this.taskFunctions.get('default') - } else { - fn = this.taskFunctions.get(message.name) - } + const fn = this.getTaskFunction(message.name) // Task message received if (fn?.constructor.name === 'AsyncFunction') { this.runInAsyncScope(this.runAsync.bind(this), this, fn, message) @@ -260,4 +258,13 @@ export abstract class AbstractWorker< }) .catch(EMPTY_FUNCTION) } + + private getTaskFunction (name?: string): WorkerFunction { + name = name ?? DEFAULT_FUNCTION_NAME + const fn = this.taskFunctions.get(name) + if (fn == null) { + throw new Error(`Task function "${name}" not found`) + } + return fn + } }