feat: add fastify poolifier integration example
[poolifier.git] / examples / typescript / http-server-pool / express / src / main.ts
CommitLineData
fac9ce96
JB
1import express, { type Express, type Request, type Response } from 'express'
2import { requestHandlerPool } from './pool.js'
3
4/**
5 * The goal of this example is to show how to use the poolifier library to create a pool of workers that can handle HTTP requests.
6 * The request handler pool can also be used as a middleware in the express stack: application or router level.
7 *
8 * The express server is still single-threaded, but the request handler pool is multi-threaded.
9 */
10
11const port = 8080
12const expressApp: Express = express()
13
14const emptyFunction = (): void => {
15 /* Intentional */
16}
17
18// Parse only JSON requests body
19expressApp.use(express.json())
20
21expressApp.all('/api/echo', (req: Request, res: Response) => {
22 requestHandlerPool
23 .execute({ body: req.body }, 'echo')
24 .then(response => {
25 return res.send(response.body).end()
26 })
27 .catch(emptyFunction)
28})
29
a8706532
JB
30try {
31 expressApp.listen(port, () => {
32 console.info(
33 `⚡️[express server]: Express server is started at http://localhost:${port}/`
34 )
35 })
36} catch (err) {
37 console.error(err)
38 process.exit(1)
39}