| 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 | FastifyWorker.fastify = Fastify({ |
| 21 | logger: true |
| 22 | }) |
| 23 | |
| 24 | FastifyWorker.fastify.all('/api/echo', (request) => { |
| 25 | return request.body |
| 26 | }) |
| 27 | |
| 28 | FastifyWorker.fastify.get<{ |
| 29 | Params: { number: number } |
| 30 | }>('/api/factorial/:number', (request) => { |
| 31 | const { number } = request.params |
| 32 | return { number: factorial(number) } |
| 33 | }) |
| 34 | |
| 35 | await FastifyWorker.fastify.listen({ port }) |
| 36 | return { |
| 37 | status: true, |
| 38 | port: (FastifyWorker.fastify.server.address() as AddressInfo).port |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | public constructor () { |
| 43 | super(FastifyWorker.startFastify) |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | export const fastifyWorker = new FastifyWorker() |