build: make eslint configuration use strict type checking
[poolifier.git] / examples / typescript / http-server-pool / express-cluster / src / worker.ts
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 class ExpressWorker extends ClusterWorker<WorkerData, WorkerResponse> {
8 private static server: Server
9
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
17 private static readonly startExpress = (
18 workerData?: WorkerData
19 ): WorkerResponse => {
20 const { port } = 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: ExpressWorker.factorial(parseInt(number)) }).end()
34 })
35
36 ExpressWorker.server = application.listen(port, () => {
37 console.info(
38 `⚡️[express server]: Express server is started in cluster worker at http://localhost:${port}/`
39 )
40 })
41 return {
42 status: true,
43 port: (ExpressWorker.server.address() as AddressInfo).port
44 }
45 }
46
47 public constructor () {
48 super(ExpressWorker.startExpress, {
49 killHandler: () => {
50 ExpressWorker.server.close()
51 }
52 })
53 }
54 }
55
56 export const expressWorker = new ExpressWorker()