refactor: cleanup object destructuration in examples
[poolifier.git] / examples / typescript / http-server-pool / fastify-worker_threads / src / fastify-poolifier.ts
CommitLineData
d2bc8d80 1import type { TransferListItem } from 'worker_threads'
6ff35e73 2import { DynamicThreadPool, availableParallelism } from 'poolifier'
a8706532
JB
3import { type FastifyPluginCallback } from 'fastify'
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 }
a8706532 23 const pool = new DynamicThreadPool<WorkerData, WorkerResponse>(
6ff35e73
JB
24 options.minWorkers as number,
25 options.maxWorkers as number,
a8706532
JB
26 options.workerFile,
27 options
28 )
29 if (!fastify.hasDecorator('pool')) {
30 fastify.decorate('pool', pool)
31 }
32 if (!fastify.hasDecorator('execute')) {
33 fastify.decorate(
34 'execute',
d2bc8d80
JB
35 async (
36 data?: WorkerData,
37 name?: string,
38 transferList?: TransferListItem[]
39 ): Promise<WorkerResponse> => await pool.execute(data, name, transferList)
a8706532
JB
40 )
41 }
b6dbd509 42 done()
a8706532
JB
43}
44
45export const fastifyPoolifier = fp(fastifyPoolifierPlugin, {
46 fastify: '4.x',
47 name: 'fastify-poolifier'
48})