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