fix: fix formatting issue.
[poolifier.git] / examples / typescript / http-server-pool / express-worker_threads / 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')
041dc05b 24 .then(response => {
fac9ce96
JB
25 return res.send(response.body).end()
26 })
27 .catch(emptyFunction)
28})
29
167c661c
JB
30expressApp.get('/api/factorial/:number', (req: Request, res: Response) => {
31 const { number } = req.params
32 requestHandlerPool
219d4044 33 .execute({ body: { number: parseInt(number) } }, 'factorial')
041dc05b 34 .then(response => {
167c661c
JB
35 return res.send(response.body).end()
36 })
37 .catch(emptyFunction)
38})
39
a8706532
JB
40try {
41 expressApp.listen(port, () => {
42 console.info(
43 `⚡️[express server]: Express server is started at http://localhost:${port}/`
44 )
45 })
46} catch (err) {
47 console.error(err)
48 process.exit(1)
49}