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