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