refactor: code cleanups
[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
66f0c14c
JB
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
8538ea4c 22 }
8538ea4c
JB
23 }
24
15a9c195
JB
25 private static readonly startExpress = (
26 workerData?: WorkerData
27 ): WorkerResponse => {
67f3f2d6 28 const { port } = workerData!
d0ed34c9 29
15a9c195
JB
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
66f0c14c 41 res
80115618
JB
42 .send({
43 number: ExpressWorker.factorial(Number.parseInt(number)).toString()
44 })
66f0c14c 45 .end()
15a9c195
JB
46 })
47
b7172bc0 48 let listenerPort: number | undefined
d0ed34c9 49 ExpressWorker.server = application.listen(port, () => {
b7172bc0 50 listenerPort = (ExpressWorker.server.address() as AddressInfo).port
15a9c195 51 console.info(
b7172bc0 52 `⚡️[express server]: Express server is started in cluster worker at http://localhost:${listenerPort}/`
15a9c195
JB
53 )
54 })
55 return {
56 status: true,
b7172bc0 57 port: listenerPort ?? port
15a9c195
JB
58 }
59 }
60
61 public constructor () {
62 super(ExpressWorker.startExpress, {
63 killHandler: () => {
64 ExpressWorker.server.close()
65 }
66 })
67 }
68}
69
70export const expressWorker = new ExpressWorker()