Commit | Line | Data |
---|---|---|
3b311539 | 1 | import type { AddressInfo } from 'node:net' |
503bda5b | 2 | import { ClusterWorker } from 'poolifier' |
3d49c6d2 | 3 | import Fastify, { type FastifyInstance } from 'fastify' |
3b311539 JB |
4 | import type { ClusterWorkerData, ClusterWorkerResponse } from './types.js' |
5 | import { fastifyPoolifier } from './fastify-poolifier.js' | |
6 | ||
3b311539 JB |
7 | class FastifyWorker extends ClusterWorker< |
8 | ClusterWorkerData, | |
9 | ClusterWorkerResponse | |
10 | > { | |
3d49c6d2 JB |
11 | private static fastify: FastifyInstance |
12 | ||
13 | private static readonly startFastify = async ( | |
14 | workerData?: ClusterWorkerData | |
15 | ): Promise<ClusterWorkerResponse> => { | |
7d9756e3 | 16 | const { port, ...fastifyPoolifierOptions } = workerData as ClusterWorkerData |
d0ed34c9 | 17 | |
3d49c6d2 JB |
18 | FastifyWorker.fastify = Fastify({ |
19 | logger: true | |
20 | }) | |
21 | ||
7d9756e3 JB |
22 | await FastifyWorker.fastify.register( |
23 | fastifyPoolifier, | |
24 | fastifyPoolifierOptions | |
25 | ) | |
3d49c6d2 | 26 | |
041dc05b | 27 | FastifyWorker.fastify.all('/api/echo', async request => { |
3d49c6d2 | 28 | return ( |
d0ed34c9 JB |
29 | await FastifyWorker.fastify.execute({ data: request.body }, 'echo') |
30 | ).data | |
3d49c6d2 JB |
31 | }) |
32 | ||
33 | FastifyWorker.fastify.get<{ | |
34 | Params: { number: number } | |
041dc05b | 35 | }>('/api/factorial/:number', async request => { |
3d49c6d2 JB |
36 | const { number } = request.params |
37 | return ( | |
d0ed34c9 JB |
38 | await FastifyWorker.fastify.execute({ data: { number } }, 'factorial') |
39 | ).data | |
3d49c6d2 JB |
40 | }) |
41 | ||
42 | await FastifyWorker.fastify.listen({ port }) | |
43 | return { | |
44 | status: true, | |
1fa0cdf5 | 45 | port: (FastifyWorker.fastify.server.address() as AddressInfo)?.port |
3d49c6d2 JB |
46 | } |
47 | } | |
48 | ||
3b311539 | 49 | public constructor () { |
5daad283 JB |
50 | super(FastifyWorker.startFastify, { |
51 | killHandler: async () => { | |
93b097ac | 52 | await FastifyWorker.fastify.pool.destroy() |
5daad283 JB |
53 | await FastifyWorker.fastify.close() |
54 | } | |
55 | }) | |
3b311539 JB |
56 | } |
57 | } | |
58 | ||
59 | export const fastifyWorker = new FastifyWorker() |