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