fix: refine type definition for transferList
[poolifier.git] / examples / typescript / http-server-pool / fastify-worker_threads / src / fastify-poolifier.ts
1 import type { TransferListItem } from 'node:worker_threads'
2
3 import type { FastifyPluginCallback } from 'fastify'
4 import fp from 'fastify-plugin'
5 import { availableParallelism, DynamicThreadPool } from 'poolifier'
6
7 import {
8 type FastifyPoolifierOptions,
9 type WorkerData,
10 type WorkerResponse
11 } from './types.js'
12
13 const fastifyPoolifierPlugin: FastifyPluginCallback<FastifyPoolifierOptions> = (
14 fastify,
15 options,
16 done
17 ) => {
18 options = {
19 ...{
20 minWorkers: 1,
21 maxWorkers: availableParallelism()
22 },
23 ...options
24 }
25 const { workerFile, minWorkers, maxWorkers, ...poolOptions } = options
26 const pool = new DynamicThreadPool<WorkerData, WorkerResponse>(
27 minWorkers!,
28 maxWorkers!,
29 workerFile,
30 poolOptions
31 )
32 if (!fastify.hasDecorator('pool')) {
33 fastify.decorate('pool', pool)
34 }
35 if (!fastify.hasDecorator('execute')) {
36 fastify.decorate(
37 'execute',
38 async (
39 data?: WorkerData,
40 name?: string,
41 transferList?: readonly TransferListItem[]
42 ): Promise<WorkerResponse> => await pool.execute(data, name, transferList)
43 )
44 }
45 done()
46 }
47
48 export const fastifyPoolifier = fp(fastifyPoolifierPlugin, {
49 fastify: '4.x',
50 name: 'fastify-poolifier'
51 })