refactor: cleanup eslint configuration
[poolifier.git] / examples / typescript / http-server-pool / fastify-hybrid / src / fastify-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 { fastifyPoolifier } from './fastify-poolifier.js'
7 import type { ClusterWorkerData, ClusterWorkerResponse } from './types.js'
8
9 class FastifyWorker extends ClusterWorker<
10 ClusterWorkerData,
11 ClusterWorkerResponse
12 > {
13 private static fastify: FastifyInstance
14
15 private static readonly startFastify = async (
16 workerData?: ClusterWorkerData
17 ): Promise<ClusterWorkerResponse> => {
18 const { port, ...fastifyPoolifierOptions } = workerData!
19
20 FastifyWorker.fastify = Fastify({
21 logger: true
22 })
23
24 await FastifyWorker.fastify.register(
25 fastifyPoolifier,
26 fastifyPoolifierOptions
27 )
28
29 FastifyWorker.fastify.all('/api/echo', async request => {
30 return (
31 await FastifyWorker.fastify.execute({ data: request.body }, 'echo')
32 ).data
33 })
34
35 FastifyWorker.fastify.get<{
36 Params: { number: number }
37 }>('/api/factorial/:number', async request => {
38 const { number } = request.params
39 return (
40 await FastifyWorker.fastify.execute({ data: { number } }, 'factorial')
41 ).data
42 })
43
44 await FastifyWorker.fastify.listen({ port })
45 return {
46 status: true,
47 port: (FastifyWorker.fastify.server.address() as AddressInfo).port
48 }
49 }
50
51 public constructor () {
52 super(FastifyWorker.startFastify, {
53 killHandler: async () => {
54 await FastifyWorker.fastify.pool.destroy()
55 await FastifyWorker.fastify.close()
56 }
57 })
58 }
59 }
60
61 export const fastifyWorker = new FastifyWorker()