| 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, ...fastifyPoolifierOptions } = workerData as ClusterWorkerData |
| 17 | |
| 18 | FastifyWorker.fastify = Fastify({ |
| 19 | logger: true |
| 20 | }) |
| 21 | |
| 22 | await FastifyWorker.fastify.register( |
| 23 | fastifyPoolifier, |
| 24 | fastifyPoolifierOptions |
| 25 | ) |
| 26 | |
| 27 | FastifyWorker.fastify.all('/api/echo', async (request) => { |
| 28 | return ( |
| 29 | await FastifyWorker.fastify.execute({ data: request.body }, 'echo') |
| 30 | ).data |
| 31 | }) |
| 32 | |
| 33 | FastifyWorker.fastify.get<{ |
| 34 | Params: { number: number } |
| 35 | }>('/api/factorial/:number', async (request) => { |
| 36 | const { number } = request.params |
| 37 | return ( |
| 38 | await FastifyWorker.fastify.execute({ data: { number } }, 'factorial') |
| 39 | ).data |
| 40 | }) |
| 41 | |
| 42 | await FastifyWorker.fastify.listen({ port }) |
| 43 | return { |
| 44 | status: true, |
| 45 | port: (FastifyWorker.fastify.server.address() as AddressInfo)?.port |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | public constructor () { |
| 50 | super(FastifyWorker.startFastify, { |
| 51 | killHandler: async () => { |
| 52 | await FastifyWorker.fastify.pool.destroy() |
| 53 | await FastifyWorker.fastify.close() |
| 54 | } |
| 55 | }) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | export const fastifyWorker = new FastifyWorker() |