X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;ds=sidebyside;f=examples%2Ftypescript%2Fhttp-server-pool%2Ffastify-cluster%2Fsrc%2Fworker.ts;h=e491fa8f4b05c3ee4712740e1e669a102775108e;hb=d3a9c958dcc326062e978f22d88747c00522032d;hp=9595fb025273501ae5582fb01ccc5f7e82837fb9;hpb=418077dfc2c940228949863ec77f414705a5b388;p=poolifier.git diff --git a/examples/typescript/http-server-pool/fastify-cluster/src/worker.ts b/examples/typescript/http-server-pool/fastify-cluster/src/worker.ts index 9595fb02..e491fa8f 100644 --- a/examples/typescript/http-server-pool/fastify-cluster/src/worker.ts +++ b/examples/typescript/http-server-pool/fastify-cluster/src/worker.ts @@ -1,51 +1,59 @@ import type { AddressInfo } from 'node:net' + +import Fastify, { type FastifyInstance } from 'fastify' import { ClusterWorker } from 'poolifier' -import Fastify from 'fastify' + import type { WorkerData, WorkerResponse } from './types.js' -const factorial: (n: number) => number = n => { - if (n === 0) { - return 1 +class FastifyWorker extends ClusterWorker { + private static fastify: FastifyInstance + + private static readonly factorial = (n: number | bigint): bigint => { + if (n === 0 || n === 1) { + return 1n + } else { + n = BigInt(n) + let factorial = 1n + for (let i = 1n; i <= n; i++) { + factorial *= i + } + return factorial + } } - return factorial(n - 1) * n -} -const startFastify = async ( - workerData?: WorkerData -): Promise => { - const fastify = Fastify({ - logger: true - }) - - fastify.all('/api/echo', request => { - return request.body - }) - - fastify.get<{ - Params: { number: number } - }>('/api/factorial/:number', request => { - const { number } = request.params - return { number: factorial(number) } - }) - - try { - await fastify.listen({ port: workerData?.port }) + private static readonly startFastify = async ( + workerData?: WorkerData + ): Promise => { + const { port } = workerData! + + FastifyWorker.fastify = Fastify({ + logger: true + }) + + FastifyWorker.fastify.all('/api/echo', request => { + return request.body + }) + + FastifyWorker.fastify.get<{ + Params: { number: number } + }>('/api/factorial/:number', request => { + const { number } = request.params + return { number: FastifyWorker.factorial(number).toString() } + }) + + await FastifyWorker.fastify.listen({ port }) return { status: true, - port: (fastify.server.address() as AddressInfo).port - } - } catch (err) { - fastify.log.error(err) - return { - status: false, - error: err as Error + port: (FastifyWorker.fastify.server.address() as AddressInfo).port } } -} -class FastifyWorker extends ClusterWorker { public constructor () { - super(startFastify) + super(FastifyWorker.startFastify, { + killHandler: async () => { + await FastifyWorker.fastify.close() + } + }) } }