build(deps-dev): apply updates
[poolifier.git] / examples / typescript / http-server-pool / fastify-hybrid / src / fastify-worker.ts
... / ...
CommitLineData
1import type { AddressInfo } from 'node:net'
2
3import Fastify, { type FastifyInstance } from 'fastify'
4import { ClusterWorker } from 'poolifier'
5
6import { fastifyPoolifier } from './fastify-poolifier.js'
7import type { ClusterWorkerData, ClusterWorkerResponse } from './types.js'
8
9class 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 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
19 const { port, ...fastifyPoolifierOptions } = workerData!
20
21 FastifyWorker.fastify = Fastify({
22 logger: true,
23 })
24
25 await FastifyWorker.fastify.register(
26 fastifyPoolifier,
27 fastifyPoolifierOptions
28 )
29
30 FastifyWorker.fastify.all('/api/echo', async request => {
31 return (
32 await FastifyWorker.fastify.execute({ data: request.body }, 'echo')
33 ).data
34 })
35
36 FastifyWorker.fastify.get<{
37 Params: { number: number }
38 }>('/api/factorial/:number', async request => {
39 const { number } = request.params
40 return (
41 await FastifyWorker.fastify.execute({ data: { number } }, 'factorial')
42 ).data
43 })
44
45 await FastifyWorker.fastify.listen({ port })
46 return {
47 status: true,
48 port: (FastifyWorker.fastify.server.address() as AddressInfo).port,
49 }
50 }
51
52 public constructor () {
53 super(FastifyWorker.startFastify, {
54 killHandler: async () => {
55 await FastifyWorker.fastify.pool.destroy()
56 await FastifyWorker.fastify.close()
57 },
58 })
59 }
60}
61
62export const fastifyWorker = new FastifyWorker()