| 1 | import type { AddressInfo } from 'node:net' |
| 2 | |
| 3 | import Fastify, { type FastifyInstance } from 'fastify' |
| 4 | import { ClusterWorker } from 'poolifier' |
| 5 | |
| 6 | import type { WorkerData, WorkerResponse } from './types.js' |
| 7 | |
| 8 | class FastifyWorker extends ClusterWorker<WorkerData, WorkerResponse> { |
| 9 | private static fastify: FastifyInstance |
| 10 | |
| 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 |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | private static readonly startFastify = async ( |
| 25 | workerData?: WorkerData |
| 26 | ): Promise<WorkerResponse> => { |
| 27 | const { port } = workerData! |
| 28 | |
| 29 | FastifyWorker.fastify = Fastify({ |
| 30 | logger: true |
| 31 | }) |
| 32 | |
| 33 | FastifyWorker.fastify.all('/api/echo', request => { |
| 34 | return request.body |
| 35 | }) |
| 36 | |
| 37 | FastifyWorker.fastify.get<{ |
| 38 | Params: { number: number } |
| 39 | }>('/api/factorial/:number', request => { |
| 40 | const { number } = request.params |
| 41 | return { number: FastifyWorker.factorial(number).toString() } |
| 42 | }) |
| 43 | |
| 44 | await FastifyWorker.fastify.listen({ port }) |
| 45 | return { |
| 46 | status: true, |
| 47 | port: (FastifyWorker.fastify.server.address() as AddressInfo).port |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | public constructor () { |
| 52 | super(FastifyWorker.startFastify, { |
| 53 | killHandler: async () => { |
| 54 | await FastifyWorker.fastify.close() |
| 55 | } |
| 56 | }) |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | export const fastifyWorker = new FastifyWorker() |