a71c0b76edf6530a44b9c4d535888a1e5c6fcb3a
[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 /**
8 * The fastify server is still a single-threaded application, but the request handling can be multi-threaded.
9 */
10
11 const port = 8080
12 const fastify = Fastify({
13 logger: true
14 })
15
16 const workerFile = join(
17 dirname(fileURLToPath(import.meta.url)),
18 `worker${extname(fileURLToPath(import.meta.url))}`
19 )
20
21 await fastify.register(fastifyPoolifier, {
22 workerFile,
23 minWorkers: 1,
24 maxWorkers: availableParallelism(),
25 enableTasksQueue: true,
26 tasksQueueOptions: {
27 concurrency: 8
28 },
29 errorHandler: (e: Error) => {
30 console.error(e)
31 }
32 })
33
34 fastify.all('/api/echo', async (request, reply) => {
35 await reply.send((await fastify.execute({ body: request.body }, 'echo')).body)
36 })
37
38 fastify.get<{
39 Params: { number: number }
40 }>('/api/factorial/:number', async (request, reply) => {
41 const { number } = request.params
42 await reply.send(
43 (await fastify.execute({ body: { number } }, 'factorial')).body
44 )
45 })
46
47 try {
48 await fastify.listen({ port })
49 } catch (err) {
50 fastify.log.error(err)
51 process.exit(1)
52 }