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