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