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