refactor: add default options values to fastify example
[poolifier.git] / examples / typescript / http-server-pool / fastify / src / main.ts
CommitLineData
a8706532
JB
1import { dirname, extname, join } from 'node:path'
2import { fileURLToPath } from 'node:url'
3import Fastify from 'fastify'
4import { availableParallelism } from 'poolifier'
5import { fastifyPoolifier } from './fastify-poolifier.js'
6
75cfb36d
JB
7/**
8 * The fastify server is still a single-threaded application, but the request handling can be multi-threaded.
9 */
10
a8706532
JB
11const port = 8080
12const fastify = Fastify({
13 logger: true
14})
15
16const workerFile = join(
17 dirname(fileURLToPath(import.meta.url)),
18 `worker${extname(fileURLToPath(import.meta.url))}`
19)
20
21await 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
34fastify.all('/api/echo', async (request, reply) => {
35 await reply.send((await fastify.execute({ body: request.body }, 'echo')).body)
36})
37
16100564
JB
38fastify.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})
a8706532
JB
46
47try {
48 await fastify.listen({ port })
49} catch (err) {
50 fastify.log.error(err)
51 process.exit(1)
52}