build(deps-dev): bump @typescript-eslint/eslint-plugin
[poolifier.git] / src / worker / utils.ts
1 import { isPlainObject } from '../utils'
2 import type { TaskFunction } from './task-functions'
3 import { KillBehaviors, type WorkerOptions } from './worker-options'
4
5 export const checkValidWorkerOptions = (opts: WorkerOptions): void => {
6 if (opts != null && !isPlainObject(opts)) {
7 throw new TypeError('opts worker options parameter is not a plain object')
8 }
9 if (
10 opts?.killBehavior != null &&
11 !Object.values(KillBehaviors).includes(opts.killBehavior)
12 ) {
13 throw new TypeError(
14 `killBehavior option '${opts.killBehavior}' is not valid`
15 )
16 }
17 if (
18 opts?.maxInactiveTime != null &&
19 !Number.isSafeInteger(opts.maxInactiveTime)
20 ) {
21 throw new TypeError('maxInactiveTime option is not an integer')
22 }
23 if (opts?.maxInactiveTime != null && opts.maxInactiveTime < 5) {
24 throw new TypeError(
25 'maxInactiveTime option is not a positive integer greater or equal than 5'
26 )
27 }
28 if (opts?.killHandler != null && typeof opts.killHandler !== 'function') {
29 throw new TypeError('killHandler option is not a function')
30 }
31 }
32
33 export const checkValidTaskFunctionEntry = <Data = unknown, Response = unknown>(
34 name: string,
35 fn: TaskFunction<Data, Response>
36 ): void => {
37 if (typeof name !== 'string') {
38 throw new TypeError('A taskFunctions parameter object key is not a string')
39 }
40 if (typeof name === 'string' && name.trim().length === 0) {
41 throw new TypeError(
42 'A taskFunctions parameter object key is an empty string'
43 )
44 }
45 if (typeof fn !== 'function') {
46 throw new TypeError(
47 'A taskFunctions parameter object value is not a function'
48 )
49 }
50 }
51
52 export const checkTaskFunctionName = (name: string): void => {
53 if (typeof name !== 'string') {
54 throw new TypeError('name parameter is not a string')
55 }
56 if (typeof name === 'string' && name.trim().length === 0) {
57 throw new TypeError('name parameter is an empty string')
58 }
59 }