feat: add multithreaded factorial computation endpoint to fastify
[poolifier.git] / examples / typescript / http-server-pool / fastify / src / main.ts
1 import { dirname, extname, join } from 'node:path'
2 import { fileURLToPath } from 'node:url'
3 import Fastify from 'fastify'
4 import { availableParallelism } from 'poolifier'
5 import { fastifyPoolifier } from './fastify-poolifier.js'
6
7 const port = 8080
8 const fastify = Fastify({
9 logger: true
10 })
11
12 const workerFile = join(
13 dirname(fileURLToPath(import.meta.url)),
14 `worker${extname(fileURLToPath(import.meta.url))}`
15 )
16
17 await fastify.register(fastifyPoolifier, {
18 workerFile,
19 minWorkers: 1,
20 maxWorkers: availableParallelism(),
21 enableTasksQueue: true,
22 tasksQueueOptions: {
23 concurrency: 8
24 },
25 errorHandler: (e: Error) => {
26 console.error(e)
27 }
28 })
29
30 fastify.all('/api/echo', async (request, reply) => {
31 await reply.send((await fastify.execute({ body: request.body }, 'echo')).body)
32 })
33
34 fastify.get<{
35 Params: { number: number }
36 }>('/api/factorial/:number', async (request, reply) => {
37 const { number } = request.params
38 await reply.send(
39 (await fastify.execute({ body: { number } }, 'factorial')).body
40 )
41 })
42
43 try {
44 await fastify.listen({ port })
45 } catch (err) {
46 fastify.log.error(err)
47 process.exit(1)
48 }