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'
6 class FastifyWorker
extends ClusterWorker
<WorkerData
, WorkerResponse
> {
7 private static fastify
: FastifyInstance
9 private static readonly factorial
= (n
: number): number => {
13 return FastifyWorker
.factorial(n
- 1) * n
16 private static readonly startFastify
= async (
17 workerData
?: WorkerData
18 ): Promise
<WorkerResponse
> => {
19 const { port
} = workerData
as WorkerData
21 FastifyWorker
.fastify
= Fastify({
25 FastifyWorker
.fastify
.all('/api/echo', request
=> {
29 FastifyWorker
.fastify
.get
<{
30 Params
: { number: number }
31 }>('/api/factorial/:number', request
=> {
32 const { number } = request
.params
33 return { number: FastifyWorker
.factorial(number) }
36 await FastifyWorker
.fastify
.listen({ port
})
39 port
: (FastifyWorker
.fastify
.server
.address() as AddressInfo
)?.port
43 public constructor () {
44 super(FastifyWorker
.startFastify
, {
45 killHandler
: async () => {
46 await FastifyWorker
.fastify
.close()
52 export const fastifyWorker
= new FastifyWorker()