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> => { | |
67f3f2d6 | 27 | const { port } = workerData! |
d0ed34c9 | 28 | |
3d49c6d2 JB |
29 | FastifyWorker.fastify = Fastify({ |
30 | logger: true | |
31 | }) | |
32 | ||
041dc05b | 33 | FastifyWorker.fastify.all('/api/echo', request => { |
3d49c6d2 JB |
34 | return request.body |
35 | }) | |
36 | ||
37 | FastifyWorker.fastify.get<{ | |
38 | Params: { number: number } | |
041dc05b | 39 | }>('/api/factorial/:number', request => { |
3d49c6d2 | 40 | const { number } = request.params |
66f0c14c | 41 | return { number: FastifyWorker.factorial(number).toString() } |
3d49c6d2 JB |
42 | }) |
43 | ||
44 | await FastifyWorker.fastify.listen({ port }) | |
45 | return { | |
46 | status: true, | |
c63a35a0 | 47 | port: (FastifyWorker.fastify.server.address() as AddressInfo).port |
3d49c6d2 | 48 | } |
418077df | 49 | } |
418077df | 50 | |
418077df | 51 | public constructor () { |
5daad283 JB |
52 | super(FastifyWorker.startFastify, { |
53 | killHandler: async () => { | |
54 | await FastifyWorker.fastify.close() | |
55 | } | |
56 | }) | |
418077df JB |
57 | } |
58 | } | |
59 | ||
60 | export const fastifyWorker = new FastifyWorker() |