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