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