Commit | Line | Data |
---|---|---|
fac9ce96 JB |
1 | import express, { type Express, type Request, type Response } from 'express' |
2 | import { 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 | ||
11 | const port = 8080 | |
12 | const expressApp: Express = express() | |
13 | ||
14 | const emptyFunction = (): void => { | |
15 | /* Intentional */ | |
16 | } | |
17 | ||
18 | // Parse only JSON requests body | |
19 | expressApp.use(express.json()) | |
20 | ||
21 | expressApp.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 |
30 | expressApp.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 |
40 | try { |
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 | } |