Commit | Line | Data |
---|---|---|
a449b585 JB |
1 | import type { Server } from 'node:http' |
2 | import type { AddressInfo } from 'node:net' | |
ded253e2 | 3 | |
15a9c195 | 4 | import express, { type Express, type Request, type Response } from 'express' |
ded253e2 JB |
5 | import { ClusterWorker } from 'poolifier' |
6 | ||
ef083f7b | 7 | import type { WorkerData, WorkerResponse } from './types.js' |
15a9c195 | 8 | |
15a9c195 | 9 | class ExpressWorker extends ClusterWorker<WorkerData, WorkerResponse> { |
97231086 | 10 | private static readonly factorial = (n: bigint | number): bigint => { |
66f0c14c JB |
11 | if (n === 0 || n === 1) { |
12 | return 1n | |
13 | } else { | |
14 | n = BigInt(n) | |
15 | let factorial = 1n | |
16 | for (let i = 1n; i <= n; i++) { | |
17 | factorial *= i | |
18 | } | |
19 | return factorial | |
8538ea4c | 20 | } |
8538ea4c JB |
21 | } |
22 | ||
97231086 JB |
23 | private static server: Server |
24 | ||
15a9c195 JB |
25 | private static readonly startExpress = ( |
26 | workerData?: WorkerData | |
27 | ): WorkerResponse => { | |
3a502712 | 28 | // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
67f3f2d6 | 29 | const { port } = workerData! |
d0ed34c9 | 30 | |
15a9c195 JB |
31 | const application: Express = express() |
32 | ||
33 | // Parse only JSON requests body | |
34 | application.use(express.json()) | |
35 | ||
36 | application.all('/api/echo', (req: Request, res: Response) => { | |
37 | res.send(req.body).end() | |
38 | }) | |
39 | ||
40 | application.get('/api/factorial/:number', (req: Request, res: Response) => { | |
41 | const { number } = req.params | |
66f0c14c | 42 | res |
80115618 | 43 | .send({ |
3a502712 | 44 | number: ExpressWorker.factorial(Number.parseInt(number)).toString(), |
80115618 | 45 | }) |
66f0c14c | 46 | .end() |
15a9c195 JB |
47 | }) |
48 | ||
b7172bc0 | 49 | let listenerPort: number | undefined |
d0ed34c9 | 50 | ExpressWorker.server = application.listen(port, () => { |
b7172bc0 | 51 | listenerPort = (ExpressWorker.server.address() as AddressInfo).port |
15a9c195 | 52 | console.info( |
6e5d7052 | 53 | `⚡️[express server]: Express server is started in cluster worker at http://localhost:${listenerPort.toString()}/` |
15a9c195 JB |
54 | ) |
55 | }) | |
56 | return { | |
3a502712 | 57 | port: listenerPort ?? port, |
97231086 | 58 | status: true, |
15a9c195 JB |
59 | } |
60 | } | |
61 | ||
62 | public constructor () { | |
63 | super(ExpressWorker.startExpress, { | |
64 | killHandler: () => { | |
65 | ExpressWorker.server.close() | |
3a502712 | 66 | }, |
15a9c195 JB |
67 | }) |
68 | } | |
69 | } | |
70 | ||
71 | export const expressWorker = new ExpressWorker() |