build: switch from prettier to rome as code formatter
[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
17 FastifyWorker.fastify = Fastify({
18 logger: true
19 })
20
21 await FastifyWorker.fastify.register(fastifyPoolifier, workerData)
22
8ebe6c30 23 FastifyWorker.fastify.all('/api/echo', async (request) => {
3d49c6d2
JB
24 return (
25 await FastifyWorker.fastify.execute({ body: request.body }, 'echo')
26 ).body
27 })
28
29 FastifyWorker.fastify.get<{
30 Params: { number: number }
8ebe6c30 31 }>('/api/factorial/:number', async (request) => {
3d49c6d2
JB
32 const { number } = request.params
33 return (
34 await FastifyWorker.fastify.execute({ body: { number } }, 'factorial')
35 ).body
36 })
37
38 await FastifyWorker.fastify.listen({ port })
39 return {
40 status: true,
41 port: (FastifyWorker.fastify.server.address() as AddressInfo).port
42 }
43 }
44
3b311539 45 public constructor () {
3d49c6d2 46 super(FastifyWorker.startFastify)
3b311539
JB
47 }
48}
49
50export const fastifyWorker = new FastifyWorker()