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