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> => { | |
16 | const { port } = workerData as ClusterWorkerData | |
d0ed34c9 | 17 | |
3d49c6d2 JB |
18 | FastifyWorker.fastify = Fastify({ |
19 | logger: true | |
20 | }) | |
21 | ||
22 | await FastifyWorker.fastify.register(fastifyPoolifier, workerData) | |
23 | ||
8ebe6c30 | 24 | FastifyWorker.fastify.all('/api/echo', async (request) => { |
3d49c6d2 | 25 | return ( |
d0ed34c9 JB |
26 | await FastifyWorker.fastify.execute({ data: request.body }, 'echo') |
27 | ).data | |
3d49c6d2 JB |
28 | }) |
29 | ||
30 | FastifyWorker.fastify.get<{ | |
31 | Params: { number: number } | |
8ebe6c30 | 32 | }>('/api/factorial/:number', async (request) => { |
3d49c6d2 JB |
33 | const { number } = request.params |
34 | return ( | |
d0ed34c9 JB |
35 | await FastifyWorker.fastify.execute({ data: { number } }, 'factorial') |
36 | ).data | |
3d49c6d2 JB |
37 | }) |
38 | ||
39 | await FastifyWorker.fastify.listen({ port }) | |
40 | return { | |
41 | status: true, | |
42 | port: (FastifyWorker.fastify.server.address() as AddressInfo).port | |
43 | } | |
44 | } | |
45 | ||
3b311539 | 46 | public constructor () { |
5daad283 JB |
47 | super(FastifyWorker.startFastify, { |
48 | killHandler: async () => { | |
93b097ac | 49 | await FastifyWorker.fastify.pool.destroy() |
5daad283 JB |
50 | await FastifyWorker.fastify.close() |
51 | } | |
52 | }) | |
3b311539 JB |
53 | } |
54 | } | |
55 | ||
56 | export const fastifyWorker = new FastifyWorker() |