refactor: renable standard JS linter rules
[poolifier.git] / examples / typescript / http-server-pool / express-cluster / src / worker.ts
CommitLineData
a449b585
JB
1import type { Server } from 'node:http'
2import type { AddressInfo } from 'node:net'
15a9c195
JB
3import { ClusterWorker } from 'poolifier'
4import express, { type Express, type Request, type Response } from 'express'
ef083f7b 5import type { WorkerData, WorkerResponse } from './types.js'
15a9c195 6
15a9c195
JB
7class ExpressWorker extends ClusterWorker<WorkerData, WorkerResponse> {
8 private static server: Server
9
8538ea4c
JB
10 private static readonly factorial = (n: number): number => {
11 if (n === 0) {
12 return 1
13 }
14 return ExpressWorker.factorial(n - 1) * n
15 }
16
15a9c195
JB
17 private static readonly startExpress = (
18 workerData?: WorkerData
19 ): WorkerResponse => {
67f3f2d6 20 const { port } = workerData!
d0ed34c9 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
8538ea4c 33 res.send({ number: ExpressWorker.factorial(parseInt(number)) }).end()
15a9c195
JB
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
57export const expressWorker = new ExpressWorker()