724836de7ef6fb5287e511a59d5cbe71cb360c22
[poolifier.git] / examples / typescript / http-server-pool / fastify-worker_threads / src / main.ts
1 import { dirname, extname, join } from 'node:path'
2 import { fileURLToPath } from 'node:url'
3 import { exit } from 'node:process'
4 import Fastify from 'fastify'
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 enableTasksQueue: true,
24 tasksQueueOptions: {
25 concurrency: 8
26 },
27 errorHandler: (e: Error) => {
28 fastify.log.error('Thread worker error:', e)
29 }
30 })
31
32 fastify.all('/api/echo', async request => {
33 return (await fastify.execute({ body: request.body }, 'echo')).body
34 })
35
36 fastify.get<{
37 Params: { number: number }
38 }>('/api/factorial/:number', async request => {
39 const { number } = request.params
40 return (await fastify.execute({ body: { number } }, 'factorial')).body
41 })
42
43 try {
44 await fastify.listen({ port })
45 } catch (err) {
46 fastify.log.error(err)
47 exit(1)
48 }