Commit | Line | Data |
---|---|---|
15a9c195 JB |
1 | import type { Server } from 'http' |
2 | import type { AddressInfo } from 'net' | |
3 | import { ClusterWorker } from 'poolifier' | |
4 | import express, { type Express, type Request, type Response } from 'express' | |
5 | import { type WorkerData, type WorkerResponse } from './types.js' | |
6 | ||
7 | const factorial: (n: number) => number = (n) => { | |
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 => { | |
20 | const application: Express = express() | |
21 | ||
22 | // Parse only JSON requests body | |
23 | application.use(express.json()) | |
24 | ||
25 | application.all('/api/echo', (req: Request, res: Response) => { | |
26 | res.send(req.body).end() | |
27 | }) | |
28 | ||
29 | application.get('/api/factorial/:number', (req: Request, res: Response) => { | |
30 | const { number } = req.params | |
31 | res.send({ number: factorial(parseInt(number)) }).end() | |
32 | }) | |
33 | ||
34 | ExpressWorker.server = application.listen(workerData?.port, () => { | |
35 | console.info( | |
36 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions | |
37 | `⚡️[express server]: Express server is started in cluster worker at http://localhost:${workerData?.port}/` | |
38 | ) | |
39 | }) | |
40 | return { | |
41 | status: true, | |
42 | port: | |
43 | (ExpressWorker.server.address() as AddressInfo)?.port ?? | |
44 | workerData?.port | |
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() |