Commit | Line | Data |
---|---|---|
3b311539 | 1 | import type { AddressInfo } from 'node:net' |
503bda5b | 2 | import { ClusterWorker } from 'poolifier' |
3b311539 JB |
3 | import Fastify from 'fastify' |
4 | import type { ClusterWorkerData, ClusterWorkerResponse } from './types.js' | |
5 | import { fastifyPoolifier } from './fastify-poolifier.js' | |
6 | ||
7 | const startFastify = async ( | |
8 | workerData?: ClusterWorkerData | |
9 | ): Promise<ClusterWorkerResponse> => { | |
10 | const { port } = workerData as ClusterWorkerData | |
11 | const fastify = Fastify({ | |
12 | logger: true | |
13 | }) | |
14 | ||
503bda5b | 15 | await fastify.register(fastifyPoolifier, workerData) |
3b311539 JB |
16 | |
17 | fastify.all('/api/echo', async request => { | |
18 | return (await fastify.execute({ body: request.body }, 'echo')).body | |
19 | }) | |
20 | ||
21 | fastify.get<{ | |
22 | Params: { number: number } | |
23 | }>('/api/factorial/:number', async request => { | |
24 | const { number } = request.params | |
25 | return (await fastify.execute({ body: { number } }, 'factorial')).body | |
26 | }) | |
27 | ||
28 | await fastify.listen({ port }) | |
29 | return { | |
30 | status: true, | |
31 | port: (fastify.server.address() as AddressInfo).port | |
32 | } | |
33 | } | |
34 | ||
35 | class FastifyWorker extends ClusterWorker< | |
36 | ClusterWorkerData, | |
37 | ClusterWorkerResponse | |
38 | > { | |
39 | public constructor () { | |
40 | super(startFastify) | |
41 | } | |
42 | } | |
43 | ||
44 | export const fastifyWorker = new FastifyWorker() |