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