refactor: avoid direct process usage
[poolifier.git] / examples / typescript / http-server-pool / express-worker_threads / src / main.ts
CommitLineData
4a6421b5 1import { exit } from 'node:process'
fac9ce96
JB
2import express, { type Express, type Request, type Response } from 'express'
3import { 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
12const port = 8080
13const expressApp: Express = express()
14
15const emptyFunction = (): void => {
16 /* Intentional */
17}
18
19// Parse only JSON requests body
20expressApp.use(express.json())
21
22expressApp.all('/api/echo', (req: Request, res: Response) => {
23 requestHandlerPool
24 .execute({ body: req.body }, 'echo')
041dc05b 25 .then(response => {
fac9ce96
JB
26 return res.send(response.body).end()
27 })
28 .catch(emptyFunction)
29})
30
167c661c
JB
31expressApp.get('/api/factorial/:number', (req: Request, res: Response) => {
32 const { number } = req.params
33 requestHandlerPool
219d4044 34 .execute({ body: { number: parseInt(number) } }, 'factorial')
041dc05b 35 .then(response => {
167c661c
JB
36 return res.send(response.body).end()
37 })
38 .catch(emptyFunction)
39})
40
a8706532
JB
41try {
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)
4a6421b5 49 exit(1)
a8706532 50}