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