From ec8fd33166d2c3d5632353d21e737e8443519dc1 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Thu, 4 May 2023 22:54:39 +0200 Subject: [PATCH] refactor: add helper to get worker function MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- src/worker/abstract-worker.ts | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) 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 + } } -- 2.34.1