refactor: cleanup eslint configuration
[poolifier.git] / examples / typescript / http-server-pool / fastify-cluster / src / worker.ts
CommitLineData
418077df 1import type { AddressInfo } from 'node:net'
ded253e2 2
3d49c6d2 3import Fastify, { type FastifyInstance } from 'fastify'
ded253e2
JB
4import { ClusterWorker } from 'poolifier'
5
418077df
JB
6import type { WorkerData, WorkerResponse } from './types.js'
7
3d49c6d2
JB
8class FastifyWorker extends ClusterWorker<WorkerData, WorkerResponse> {
9 private static fastify: FastifyInstance
10
8538ea4c
JB
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
3d49c6d2
JB
18 private static readonly startFastify = async (
19 workerData?: WorkerData
20 ): Promise<WorkerResponse> => {
67f3f2d6 21 const { port } = workerData!
d0ed34c9 22
3d49c6d2
JB
23 FastifyWorker.fastify = Fastify({
24 logger: true
25 })
26
041dc05b 27 FastifyWorker.fastify.all('/api/echo', request => {
3d49c6d2
JB
28 return request.body
29 })
30
31 FastifyWorker.fastify.get<{
32 Params: { number: number }
041dc05b 33 }>('/api/factorial/:number', request => {
3d49c6d2 34 const { number } = request.params
8538ea4c 35 return { number: FastifyWorker.factorial(number) }
3d49c6d2
JB
36 })
37
38 await FastifyWorker.fastify.listen({ port })
39 return {
40 status: true,
c63a35a0 41 port: (FastifyWorker.fastify.server.address() as AddressInfo).port
3d49c6d2 42 }
418077df 43 }
418077df 44
418077df 45 public constructor () {
5daad283
JB
46 super(FastifyWorker.startFastify, {
47 killHandler: async () => {
48 await FastifyWorker.fastify.close()
49 }
50 })
418077df
JB
51 }
52}
53
54export const fastifyWorker = new FastifyWorker()