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