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