| 1 | import type { Server } from 'node:http' |
| 2 | import type { AddressInfo } from 'node:net' |
| 3 | import { ClusterWorker } from 'poolifier' |
| 4 | import express, { type Express, type Request, type Response } from 'express' |
| 5 | import type { WorkerData, 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 { port } = workerData as WorkerData |
| 21 | |
| 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 | |
| 36 | ExpressWorker.server = application.listen(port, () => { |
| 37 | console.info( |
| 38 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions |
| 39 | `⚡️[express server]: Express server is started in cluster worker at http://localhost:${port}/` |
| 40 | ) |
| 41 | }) |
| 42 | return { |
| 43 | status: true, |
| 44 | port: (ExpressWorker.server.address() as AddressInfo)?.port ?? 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() |