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