fix: refine type definition for transferList
[poolifier.git] / examples / typescript / http-server-pool / fastify-hybrid / src / fastify-poolifier.ts
CommitLineData
a449b585 1import type { TransferListItem } from 'node:worker_threads'
ded253e2 2
ef083f7b 3import type { FastifyPluginCallback } from 'fastify'
3b311539 4import fp from 'fastify-plugin'
ded253e2
JB
5import { availableParallelism, DynamicThreadPool } from 'poolifier'
6
3b311539
JB
7import {
8 type FastifyPoolifierOptions,
9 type ThreadWorkerData,
10 type ThreadWorkerResponse
11} from './types.js'
12
13const fastifyPoolifierPlugin: FastifyPluginCallback<FastifyPoolifierOptions> = (
14 fastify,
15 options,
16 done
17) => {
18 options = {
19 ...{
20 minWorkers: 1,
21 maxWorkers: availableParallelism()
22 },
23 ...options
24 }
30369cc0 25 const { workerFile, minWorkers, maxWorkers, ...poolOptions } = options
3b311539 26 const pool = new DynamicThreadPool<ThreadWorkerData, ThreadWorkerResponse>(
67f3f2d6
JB
27 minWorkers!,
28 maxWorkers!,
30369cc0
JB
29 workerFile,
30 poolOptions
3b311539
JB
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?: ThreadWorkerData,
40 name?: string,
6a3ecc50 41 transferList?: readonly TransferListItem[]
3b311539
JB
42 ): Promise<ThreadWorkerResponse> =>
43 await pool.execute(data, name, transferList)
44 )
45 }
46 done()
47}
48
49export const fastifyPoolifier = fp(fastifyPoolifierPlugin, {
50 fastify: '4.x',
51 name: 'fastify-poolifier'
52})