| 1 | import { dirname, extname, join } from 'node:path' |
| 2 | import { fileURLToPath } from 'node:url' |
| 3 | import Fastify from 'fastify' |
| 4 | import { availableParallelism } from 'poolifier' |
| 5 | import { fastifyPoolifier } from './fastify-poolifier.js' |
| 6 | |
| 7 | const port = 8080 |
| 8 | const fastify = Fastify({ |
| 9 | logger: true |
| 10 | }) |
| 11 | |
| 12 | const workerFile = join( |
| 13 | dirname(fileURLToPath(import.meta.url)), |
| 14 | `worker${extname(fileURLToPath(import.meta.url))}` |
| 15 | ) |
| 16 | |
| 17 | await fastify.register(fastifyPoolifier, { |
| 18 | workerFile, |
| 19 | minWorkers: 1, |
| 20 | maxWorkers: availableParallelism(), |
| 21 | enableTasksQueue: true, |
| 22 | tasksQueueOptions: { |
| 23 | concurrency: 8 |
| 24 | }, |
| 25 | errorHandler: (e: Error) => { |
| 26 | console.error(e) |
| 27 | } |
| 28 | }) |
| 29 | |
| 30 | fastify.all('/api/echo', async (request, reply) => { |
| 31 | await reply.send((await fastify.execute({ body: request.body }, 'echo')).body) |
| 32 | }) |
| 33 | |
| 34 | // fastify.get('/api/factorial/:number', async (request, reply) => { |
| 35 | // const { number } = request.params |
| 36 | // await reply.send((await fastify.execute({ body: { number } }, 'factorial')).body) |
| 37 | // }) |
| 38 | |
| 39 | try { |
| 40 | await fastify.listen({ port }) |
| 41 | } catch (err) { |
| 42 | fastify.log.error(err) |
| 43 | process.exit(1) |
| 44 | } |