| 1 | import { exit } from 'node:process' |
| 2 | |
| 3 | import express, { type Express, type Request, type Response } from 'express' |
| 4 | |
| 5 | import { requestHandlerPool } from './pool.js' |
| 6 | |
| 7 | /** |
| 8 | * 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. |
| 9 | * The request handler pool can also be used as a middleware in the express stack: application or router level. |
| 10 | * |
| 11 | * The express server is still single-threaded, but the request handler pool is multi-threaded. |
| 12 | */ |
| 13 | |
| 14 | const port = 8080 |
| 15 | const expressApp: Express = express() |
| 16 | |
| 17 | const emptyFunction = (): void => { |
| 18 | /* Intentional */ |
| 19 | } |
| 20 | |
| 21 | // Parse only JSON requests body |
| 22 | expressApp.use(express.json()) |
| 23 | |
| 24 | expressApp.all('/api/echo', (req: Request, res: Response) => { |
| 25 | requestHandlerPool |
| 26 | .execute({ body: req.body }, 'echo') |
| 27 | .then(response => { |
| 28 | return res.send(response.body).end() |
| 29 | }) |
| 30 | .catch(emptyFunction) |
| 31 | }) |
| 32 | |
| 33 | expressApp.get('/api/factorial/:number', (req: Request, res: Response) => { |
| 34 | const { number } = req.params |
| 35 | requestHandlerPool |
| 36 | .execute({ body: { number: parseInt(number) } }, 'factorial') |
| 37 | .then(response => { |
| 38 | return res.send(response.body).end() |
| 39 | }) |
| 40 | .catch(emptyFunction) |
| 41 | }) |
| 42 | |
| 43 | try { |
| 44 | expressApp.listen(port, () => { |
| 45 | console.info( |
| 46 | `⚡️[express server]: Express server is started at http://localhost:${port}/` |
| 47 | ) |
| 48 | }) |
| 49 | } catch (err) { |
| 50 | console.error(err) |
| 51 | exit(1) |
| 52 | } |