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