chore: migrate to eslint 9
[poolifier.git] / examples / typescript / http-server-pool / fastify-hybrid / src / fastify-worker.ts
CommitLineData
3b311539 1import type { AddressInfo } from 'node:net'
ded253e2 2
3d49c6d2 3import Fastify, { type FastifyInstance } from 'fastify'
ded253e2
JB
4import { ClusterWorker } from 'poolifier'
5
3b311539 6import { fastifyPoolifier } from './fastify-poolifier.js'
ded253e2 7import type { ClusterWorkerData, ClusterWorkerResponse } from './types.js'
3b311539 8
3b311539 9class FastifyWorker extends ClusterWorker<
3a502712
JB
10 ClusterWorkerData,
11 ClusterWorkerResponse
3b311539 12> {
3d49c6d2
JB
13 private static fastify: FastifyInstance
14
15 private static readonly startFastify = async (
16 workerData?: ClusterWorkerData
17 ): Promise<ClusterWorkerResponse> => {
3a502712 18 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
67f3f2d6 19 const { port, ...fastifyPoolifierOptions } = workerData!
d0ed34c9 20
3d49c6d2 21 FastifyWorker.fastify = Fastify({
3a502712 22 logger: true,
3d49c6d2
JB
23 })
24
7d9756e3
JB
25 await FastifyWorker.fastify.register(
26 fastifyPoolifier,
27 fastifyPoolifierOptions
28 )
3d49c6d2 29
041dc05b 30 FastifyWorker.fastify.all('/api/echo', async request => {
3d49c6d2 31 return (
d0ed34c9
JB
32 await FastifyWorker.fastify.execute({ data: request.body }, 'echo')
33 ).data
3d49c6d2
JB
34 })
35
36 FastifyWorker.fastify.get<{
37 Params: { number: number }
041dc05b 38 }>('/api/factorial/:number', async request => {
3d49c6d2
JB
39 const { number } = request.params
40 return (
d0ed34c9
JB
41 await FastifyWorker.fastify.execute({ data: { number } }, 'factorial')
42 ).data
3d49c6d2
JB
43 })
44
45 await FastifyWorker.fastify.listen({ port })
46 return {
47 status: true,
3a502712 48 port: (FastifyWorker.fastify.server.address() as AddressInfo).port,
3d49c6d2
JB
49 }
50 }
51
3b311539 52 public constructor () {
5daad283
JB
53 super(FastifyWorker.startFastify, {
54 killHandler: async () => {
93b097ac 55 await FastifyWorker.fastify.pool.destroy()
5daad283 56 await FastifyWorker.fastify.close()
3a502712 57 },
5daad283 58 })
3b311539
JB
59 }
60}
61
62export const fastifyWorker = new FastifyWorker()