build: make eslint configuration use strict type checking
[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 37 console.info(
d0ed34c9 38 `⚡️[express server]: Express server is started in cluster worker at http://localhost:${port}/`
15a9c195
JB
39 )
40 })
41 return {
42 status: true,
c63a35a0 43 port: (ExpressWorker.server.address() as AddressInfo).port
15a9c195
JB
44 }
45 }
46
47 public constructor () {
48 super(ExpressWorker.startExpress, {
49 killHandler: () => {
50 ExpressWorker.server.close()
51 }
52 })
53 }
54}
55
56export const expressWorker = new ExpressWorker()