dc70d7ec03a0ceb8589863b615a63e178e0c72b2
[poolifier.git] / examples / typescript / http-server-pool / express-worker_threads / src / main.ts
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 // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
27 .execute({ body: req.body }, 'echo')
28 .then(response => {
29 return res.send(response.body).end()
30 })
31 .catch(emptyFunction)
32 })
33
34 expressApp.get('/api/factorial/:number', (req: Request, res: Response) => {
35 const { number } = req.params
36 requestHandlerPool
37 .execute({ body: { number: Number.parseInt(number) } }, 'factorial')
38 .then(response => {
39 return res.send(response.body).end()
40 })
41 .catch(emptyFunction)
42 })
43
44 try {
45 expressApp.listen(port, () => {
46 console.info(
47 `⚡️[express server]: Express server is started at http://localhost:${port.toString()}/`
48 )
49 })
50 } catch (err) {
51 console.error(err)
52 exit(1)
53 }