refactor: cleanup eslint configuration
[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'
ded253e2 3
15a9c195 4import express, { type Express, type Request, type Response } from 'express'
ded253e2
JB
5import { ClusterWorker } from 'poolifier'
6
ef083f7b 7import type { WorkerData, WorkerResponse } from './types.js'
15a9c195 8
15a9c195
JB
9class ExpressWorker extends ClusterWorker<WorkerData, WorkerResponse> {
10 private static server: Server
11
8538ea4c
JB
12 private static readonly factorial = (n: number): number => {
13 if (n === 0) {
14 return 1
15 }
16 return ExpressWorker.factorial(n - 1) * n
17 }
18
15a9c195
JB
19 private static readonly startExpress = (
20 workerData?: WorkerData
21 ): WorkerResponse => {
67f3f2d6 22 const { port } = workerData!
d0ed34c9 23
15a9c195
JB
24 const application: Express = express()
25
26 // Parse only JSON requests body
27 application.use(express.json())
28
29 application.all('/api/echo', (req: Request, res: Response) => {
30 res.send(req.body).end()
31 })
32
33 application.get('/api/factorial/:number', (req: Request, res: Response) => {
34 const { number } = req.params
8538ea4c 35 res.send({ number: ExpressWorker.factorial(parseInt(number)) }).end()
15a9c195
JB
36 })
37
d0ed34c9 38 ExpressWorker.server = application.listen(port, () => {
15a9c195 39 console.info(
d0ed34c9 40 `⚡️[express server]: Express server is started in cluster worker at http://localhost:${port}/`
15a9c195
JB
41 )
42 })
43 return {
44 status: true,
c63a35a0 45 port: (ExpressWorker.server.address() as AddressInfo).port
15a9c195
JB
46 }
47 }
48
49 public constructor () {
50 super(ExpressWorker.startExpress, {
51 killHandler: () => {
52 ExpressWorker.server.close()
53 }
54 })
55 }
56}
57
58export const expressWorker = new ExpressWorker()