Commit | Line | Data |
---|---|---|
3b311539 | 1 | import type { AddressInfo } from 'node:net' |
503bda5b | 2 | import { ClusterWorker } from 'poolifier' |
3d49c6d2 | 3 | import Fastify, { type FastifyInstance } from 'fastify' |
3b311539 JB |
4 | import type { ClusterWorkerData, ClusterWorkerResponse } from './types.js' |
5 | import { fastifyPoolifier } from './fastify-poolifier.js' | |
6 | ||
3b311539 JB |
7 | class FastifyWorker extends ClusterWorker< |
8 | ClusterWorkerData, | |
9 | ClusterWorkerResponse | |
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 | ||
50 | export const fastifyWorker = new FastifyWorker() |