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') | |
24 | .then(response => { | |
25 | return res.send(response.body).end() | |
26 | }) | |
27 | .catch(emptyFunction) | |
28 | }) | |
29 | ||
a8706532 JB |
30 | try { |
31 | expressApp.listen(port, () => { | |
32 | console.info( | |
33 | `⚡️[express server]: Express server is started at http://localhost:${port}/` | |
34 | ) | |
35 | }) | |
36 | } catch (err) { | |
37 | console.error(err) | |
38 | process.exit(1) | |
39 | } |