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