feat: add task function properties support
[poolifier.git] / src / worker / utils.ts
CommitLineData
31847469 1import { checkValidWorkerChoiceStrategy } from '../pools/utils.js'
d35e5717 2import { isPlainObject } from '../utils.js'
31847469 3import type { TaskFunctionObject } from './task-functions.js'
d35e5717 4import { KillBehaviors, type WorkerOptions } from './worker-options.js'
9a38f99e 5
c63a35a0
JB
6export const checkValidWorkerOptions = (
7 opts: WorkerOptions | undefined
8): void => {
9a38f99e
JB
9 if (opts != null && !isPlainObject(opts)) {
10 throw new TypeError('opts worker options parameter is not a plain object')
11 }
12 if (
13 opts?.killBehavior != null &&
14 !Object.values(KillBehaviors).includes(opts.killBehavior)
15 ) {
16 throw new TypeError(
17 `killBehavior option '${opts.killBehavior}' is not valid`
18 )
19 }
20 if (
21 opts?.maxInactiveTime != null &&
22 !Number.isSafeInteger(opts.maxInactiveTime)
23 ) {
24 throw new TypeError('maxInactiveTime option is not an integer')
25 }
26 if (opts?.maxInactiveTime != null && opts.maxInactiveTime < 5) {
27 throw new TypeError(
28 'maxInactiveTime option is not a positive integer greater or equal than 5'
29 )
30 }
31 if (opts?.killHandler != null && typeof opts.killHandler !== 'function') {
32 throw new TypeError('killHandler option is not a function')
33 }
9a38f99e
JB
34}
35
36export const checkValidTaskFunctionEntry = <Data = unknown, Response = unknown>(
37 name: string,
31847469 38 fnObj: TaskFunctionObject<Data, Response>
9a38f99e
JB
39): void => {
40 if (typeof name !== 'string') {
41 throw new TypeError('A taskFunctions parameter object key is not a string')
42 }
43 if (typeof name === 'string' && name.trim().length === 0) {
44 throw new TypeError(
45 'A taskFunctions parameter object key is an empty string'
46 )
47 }
31847469 48 if (typeof fnObj.taskFunction !== 'function') {
9a38f99e 49 throw new TypeError(
31847469
JB
50 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
51 `taskFunction object 'taskFunction' property '${fnObj.taskFunction}' is not a function`
9a38f99e
JB
52 )
53 }
31847469
JB
54 if (fnObj.priority != null && !Number.isSafeInteger(fnObj.priority)) {
55 throw new TypeError(
56 `taskFunction object 'priority' property '${fnObj.priority}' is not an integer`
57 )
58 }
59 checkValidWorkerChoiceStrategy(fnObj.strategy)
9a38f99e
JB
60}
61
62export const checkTaskFunctionName = (name: string): void => {
63 if (typeof name !== 'string') {
64 throw new TypeError('name parameter is not a string')
65 }
66 if (typeof name === 'string' && name.trim().length === 0) {
67 throw new TypeError('name parameter is an empty string')
68 }
69}