| 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 } = workerData as ClusterWorkerData |
| 17 | FastifyWorker.fastify = Fastify({ |
| 18 | logger: true |
| 19 | }) |
| 20 | |
| 21 | await FastifyWorker.fastify.register(fastifyPoolifier, workerData) |
| 22 | |
| 23 | FastifyWorker.fastify.all('/api/echo', async (request) => { |
| 24 | return ( |
| 25 | await FastifyWorker.fastify.execute({ body: request.body }, 'echo') |
| 26 | ).body |
| 27 | }) |
| 28 | |
| 29 | FastifyWorker.fastify.get<{ |
| 30 | Params: { number: number } |
| 31 | }>('/api/factorial/:number', async (request) => { |
| 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 | |
| 45 | public constructor () { |
| 46 | super(FastifyWorker.startFastify, { |
| 47 | killHandler: async () => { |
| 48 | await FastifyWorker.fastify.pool.destroy() |
| 49 | await FastifyWorker.fastify.close() |
| 50 | } |
| 51 | }) |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | export const fastifyWorker = new FastifyWorker() |