Commit | Line | Data |
---|---|---|
a8706532 | 1 | import { dirname, extname, join } from 'node:path' |
4a6421b5 | 2 | import { exit } from 'node:process' |
ded253e2 JB |
3 | import { fileURLToPath } from 'node:url' |
4 | ||
a8706532 | 5 | import Fastify from 'fastify' |
ded253e2 | 6 | |
a8706532 JB |
7 | import { 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 |
13 | const port = 8080 |
14 | const fastify = Fastify({ | |
15 | logger: true | |
16 | }) | |
17 | ||
18 | const workerFile = join( | |
19 | dirname(fileURLToPath(import.meta.url)), | |
20 | `worker${extname(fileURLToPath(import.meta.url))}` | |
21 | ) | |
22 | ||
23 | await fastify.register(fastifyPoolifier, { | |
24 | workerFile, | |
a8706532 JB |
25 | enableTasksQueue: true, |
26 | tasksQueueOptions: { | |
27 | concurrency: 8 | |
28 | }, | |
29 | errorHandler: (e: Error) => { | |
3b311539 | 30 | fastify.log.error('Thread worker error:', e) |
a8706532 JB |
31 | } |
32 | }) | |
33 | ||
041dc05b | 34 | fastify.all('/api/echo', async request => { |
d68ce4c6 | 35 | return (await fastify.execute({ body: request.body }, 'echo')).body |
a8706532 JB |
36 | }) |
37 | ||
16100564 JB |
38 | fastify.get<{ |
39 | Params: { number: number } | |
041dc05b | 40 | }>('/api/factorial/:number', async request => { |
16100564 | 41 | const { number } = request.params |
d68ce4c6 | 42 | return (await fastify.execute({ body: { number } }, 'factorial')).body |
16100564 | 43 | }) |
a8706532 JB |
44 | |
45 | try { | |
46 | await fastify.listen({ port }) | |
47 | } catch (err) { | |
48 | fastify.log.error(err) | |
4a6421b5 | 49 | exit(1) |
a8706532 | 50 | } |