feat: add fastify poolifier integration example
[poolifier.git] / examples / typescript / http-server-pool / fastify / src / fastify-poolifier.ts
1 import { DynamicThreadPool } from 'poolifier'
2 import { type FastifyPluginCallback } from 'fastify'
3 import fp from 'fastify-plugin'
4 import {
5 type FastifyPoolifierOptions,
6 type WorkerData,
7 type WorkerResponse
8 } from './types.js'
9
10 const fastifyPoolifierPlugin: FastifyPluginCallback<FastifyPoolifierOptions> = (
11 fastify,
12 options,
13 done
14 ): void => {
15 const pool = new DynamicThreadPool<WorkerData, WorkerResponse>(
16 options.minWorkers,
17 options.maxWorkers,
18 options.workerFile,
19 options
20 )
21 if (!fastify.hasDecorator('pool')) {
22 fastify.decorate('pool', pool)
23 }
24 if (!fastify.hasDecorator('execute')) {
25 fastify.decorate(
26 'execute',
27 async (data?: WorkerData, name?: string): Promise<WorkerResponse> =>
28 await pool.execute(data, name)
29 )
30 }
31 done()
32 }
33
34 export const fastifyPoolifier = fp(fastifyPoolifierPlugin, {
35 fastify: '4.x',
36 name: 'fastify-poolifier'
37 })