Commit | Line | Data |
---|---|---|
a8706532 JB |
1 | import { dirname, extname, join } from 'node:path' |
2 | import { fileURLToPath } from 'node:url' | |
4a6421b5 | 3 | import { exit } from 'node:process' |
a8706532 | 4 | import Fastify from 'fastify' |
a8706532 JB |
5 | import { 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 |
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, | |
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 | 32 | fastify.all('/api/echo', async request => { |
d68ce4c6 | 33 | return (await fastify.execute({ body: request.body }, 'echo')).body |
a8706532 JB |
34 | }) |
35 | ||
16100564 JB |
36 | fastify.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 | |
43 | try { | |
44 | await fastify.listen({ port }) | |
45 | } catch (err) { | |
46 | fastify.log.error(err) | |
4a6421b5 | 47 | exit(1) |
a8706532 | 48 | } |