8f4442ed748d3fd2abc62c108d361aa6f565d2e6
[poolifier.git] / examples / typescript / http-server-pool / fastify-cluster / src / worker.ts
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): number => {
12 if (n === 0) {
13 return 1
14 }
15 return FastifyWorker.factorial(n - 1) * n
16 }
17
18 private static readonly startFastify = async (
19 workerData?: WorkerData
20 ): Promise<WorkerResponse> => {
21 const { port } = workerData!
22
23 FastifyWorker.fastify = Fastify({
24 logger: true
25 })
26
27 FastifyWorker.fastify.all('/api/echo', request => {
28 return request.body
29 })
30
31 FastifyWorker.fastify.get<{
32 Params: { number: number }
33 }>('/api/factorial/:number', request => {
34 const { number } = request.params
35 return { number: FastifyWorker.factorial(number) }
36 })
37
38 await FastifyWorker.fastify.listen({ port })
39 return {
40 status: true,
41 port: (FastifyWorker.fastify.server.address() as AddressInfo).port
42 }
43 }
44
45 public constructor () {
46 super(FastifyWorker.startFastify, {
47 killHandler: async () => {
48 await FastifyWorker.fastify.close()
49 }
50 })
51 }
52 }
53
54 export const fastifyWorker = new FastifyWorker()