Commit | Line | Data |
---|---|---|
a8706532 JB |
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 | |
e18b3556 | 14 | ) => { |
a8706532 JB |
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 | }) |