Commit | Line | Data |
---|---|---|
a449b585 JB |
1 | import type { Server } from 'node:http' |
2 | import type { AddressInfo } from 'node:net' | |
15a9c195 JB |
3 | import { ClusterWorker } from 'poolifier' |
4 | import express, { type Express, type Request, type Response } from 'express' | |
ef083f7b | 5 | import type { WorkerData, WorkerResponse } from './types.js' |
15a9c195 | 6 | |
041dc05b | 7 | const factorial: (n: number) => number = n => { |
15a9c195 JB |
8 | if (n === 0) { |
9 | return 1 | |
10 | } | |
11 | return factorial(n - 1) * n | |
12 | } | |
13 | ||
14 | class ExpressWorker extends ClusterWorker<WorkerData, WorkerResponse> { | |
15 | private static server: Server | |
16 | ||
17 | private static readonly startExpress = ( | |
18 | workerData?: WorkerData | |
19 | ): WorkerResponse => { | |
d0ed34c9 JB |
20 | const { port } = workerData as WorkerData |
21 | ||
15a9c195 JB |
22 | const application: Express = express() |
23 | ||
24 | // Parse only JSON requests body | |
25 | application.use(express.json()) | |
26 | ||
27 | application.all('/api/echo', (req: Request, res: Response) => { | |
28 | res.send(req.body).end() | |
29 | }) | |
30 | ||
31 | application.get('/api/factorial/:number', (req: Request, res: Response) => { | |
32 | const { number } = req.params | |
33 | res.send({ number: factorial(parseInt(number)) }).end() | |
34 | }) | |
35 | ||
d0ed34c9 | 36 | ExpressWorker.server = application.listen(port, () => { |
15a9c195 JB |
37 | console.info( |
38 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions | |
d0ed34c9 | 39 | `⚡️[express server]: Express server is started in cluster worker at http://localhost:${port}/` |
15a9c195 JB |
40 | ) |
41 | }) | |
42 | return { | |
43 | status: true, | |
d0ed34c9 | 44 | port: (ExpressWorker.server.address() as AddressInfo)?.port ?? port |
15a9c195 JB |
45 | } |
46 | } | |
47 | ||
48 | public constructor () { | |
49 | super(ExpressWorker.startExpress, { | |
50 | killHandler: () => { | |
51 | ExpressWorker.server.close() | |
52 | } | |
53 | }) | |
54 | } | |
55 | } | |
56 | ||
57 | export const expressWorker = new ExpressWorker() |