Merge dependabot/npm_and_yarn/examples/typescript/http-server-pool/fastify-hybrid...
[poolifier.git] / examples / typescript / http-server-pool / fastify-hybrid / src / fastify-worker.ts
index dd77f1238a90a203185f1fe2a9ae4b803d378e5f..4a697f3e255def59329478440f5f8d7ca205737e 100644 (file)
@@ -1,29 +1,36 @@
 import type { AddressInfo } from 'node:net'
-import { ClusterWorker } from 'poolifier'
+
 import Fastify, { type FastifyInstance } from 'fastify'
-import type { ClusterWorkerData, ClusterWorkerResponse } from './types.js'
+import { ClusterWorker } from 'poolifier'
+
 import { fastifyPoolifier } from './fastify-poolifier.js'
+import type { ClusterWorkerData, ClusterWorkerResponse } from './types.js'
 
 class FastifyWorker extends ClusterWorker<
-ClusterWorkerData,
-ClusterWorkerResponse
+  ClusterWorkerData,
+  ClusterWorkerResponse
 > {
   private static fastify: FastifyInstance
 
   private static readonly startFastify = async (
     workerData?: ClusterWorkerData
   ): Promise<ClusterWorkerResponse> => {
-    const { port } = workerData as ClusterWorkerData
+    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+    const { port, ...fastifyPoolifierOptions } = workerData!
+
     FastifyWorker.fastify = Fastify({
-      logger: true
+      logger: true,
     })
 
-    await FastifyWorker.fastify.register(fastifyPoolifier, workerData)
+    await FastifyWorker.fastify.register(
+      fastifyPoolifier,
+      fastifyPoolifierOptions
+    )
 
     FastifyWorker.fastify.all('/api/echo', async request => {
       return (
-        await FastifyWorker.fastify.execute({ body: request.body }, 'echo')
-      ).body
+        await FastifyWorker.fastify.execute({ data: request.body }, 'echo')
+      ).data
     })
 
     FastifyWorker.fastify.get<{
@@ -31,19 +38,24 @@ ClusterWorkerResponse
     }>('/api/factorial/:number', async request => {
       const { number } = request.params
       return (
-        await FastifyWorker.fastify.execute({ body: { number } }, 'factorial')
-      ).body
+        await FastifyWorker.fastify.execute({ data: { number } }, 'factorial')
+      ).data
     })
 
     await FastifyWorker.fastify.listen({ port })
     return {
       status: true,
-      port: (FastifyWorker.fastify.server.address() as AddressInfo).port
+      port: (FastifyWorker.fastify.server.address() as AddressInfo).port,
     }
   }
 
   public constructor () {
-    super(FastifyWorker.startFastify)
+    super(FastifyWorker.startFastify, {
+      killHandler: async () => {
+        await FastifyWorker.fastify.pool.destroy()
+        await FastifyWorker.fastify.close()
+      },
+    })
   }
 }