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