Commit | Line | Data |
---|---|---|
418077df | 1 | import type { AddressInfo } from 'node:net' |
ded253e2 | 2 | |
3d49c6d2 | 3 | import Fastify, { type FastifyInstance } from 'fastify' |
ded253e2 JB |
4 | import { ClusterWorker } from 'poolifier' |
5 | ||
418077df JB |
6 | import type { WorkerData, WorkerResponse } from './types.js' |
7 | ||
3d49c6d2 JB |
8 | class FastifyWorker extends ClusterWorker<WorkerData, WorkerResponse> { |
9 | private static fastify: FastifyInstance | |
10 | ||
66f0c14c JB |
11 | private static readonly factorial = (n: number | bigint): bigint => { |
12 | if (n === 0 || n === 1) { | |
13 | return 1n | |
14 | } else { | |
15 | n = BigInt(n) | |
16 | let factorial = 1n | |
17 | for (let i = 1n; i <= n; i++) { | |
18 | factorial *= i | |
19 | } | |
20 | return factorial | |
8538ea4c | 21 | } |
8538ea4c JB |
22 | } |
23 | ||
3d49c6d2 JB |
24 | private static readonly startFastify = async ( |
25 | workerData?: WorkerData | |
26 | ): Promise<WorkerResponse> => { | |
3a502712 | 27 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
67f3f2d6 | 28 | const { port } = workerData! |
d0ed34c9 | 29 | |
3d49c6d2 | 30 | FastifyWorker.fastify = Fastify({ |
3a502712 | 31 | logger: true, |
3d49c6d2 JB |
32 | }) |
33 | ||
041dc05b | 34 | FastifyWorker.fastify.all('/api/echo', request => { |
3d49c6d2 JB |
35 | return request.body |
36 | }) | |
37 | ||
38 | FastifyWorker.fastify.get<{ | |
39 | Params: { number: number } | |
041dc05b | 40 | }>('/api/factorial/:number', request => { |
3d49c6d2 | 41 | const { number } = request.params |
66f0c14c | 42 | return { number: FastifyWorker.factorial(number).toString() } |
3d49c6d2 JB |
43 | }) |
44 | ||
45 | await FastifyWorker.fastify.listen({ port }) | |
46 | return { | |
47 | status: true, | |
3a502712 | 48 | port: (FastifyWorker.fastify.server.address() as AddressInfo).port, |
3d49c6d2 | 49 | } |
418077df | 50 | } |
418077df | 51 | |
418077df | 52 | public constructor () { |
5daad283 JB |
53 | super(FastifyWorker.startFastify, { |
54 | killHandler: async () => { | |
55 | await FastifyWorker.fastify.close() | |
3a502712 | 56 | }, |
5daad283 | 57 | }) |
418077df JB |
58 | } |
59 | } | |
60 | ||
61 | export const fastifyWorker = new FastifyWorker() |