1- import type { Server as HttpServer } from "node:http" ;
21import express , {
32 type Express ,
43 type Request ,
54 type Response ,
65 type NextFunction ,
76} from "express" ;
7+ import type { Server as HttpServer } from "node:http" ;
88
99/**
1010 * Interface for Express-based handlers
1111 */
1212export interface ExpressServerOptions {
13- /**
14- * The port to run the server on
15- */
1613 port : number ;
17-
18- /**
19- * Server type name for logging purposes
20- */
2114 serverType : string ;
22-
23- /**
24- * Custom cleanup function to be called when the server is shutting down
25- */
2615 cleanup ?: ( ) => void ;
2716}
2817
2918/**
30- * Handles CORS middleware for Express
19+ * Sets up CORS, common endpoints and middleware
3120 */
32- function setupCORS ( app : Express ) : void {
21+ function setupMiddleware ( app : Express ) : void {
22+ // CORS middleware
3323 app . use ( ( req , res , next ) => {
3424 if ( req . headers . origin ) {
3525 try {
@@ -49,24 +39,14 @@ function setupCORS(app: Express): void {
4939 } ) ;
5040
5141 // Handle OPTIONS requests
52- app . options ( "*" , ( req , res ) => {
53- res . status ( 204 ) . end ( ) ;
54- } ) ;
55- }
42+ app . options ( "*" , ( req , res ) => res . status ( 204 ) . end ( ) ) ;
5643
57- /**
58- * Sets up common endpoints like health check and ping
59- */
60- function setupCommonEndpoints ( app : Express ) : void {
61- // Health check endpoint
62- app . get ( "/health" , ( req , res ) => {
63- res . status ( 200 ) . type ( "text/plain" ) . send ( "OK" ) ;
64- } ) ;
44+ // Parse JSON requests
45+ app . use ( express . json ( ) ) ;
6546
66- // Ping endpoint
67- app . get ( "/ping" , ( req , res ) => {
68- res . status ( 200 ) . send ( "pong" ) ;
69- } ) ;
47+ // Health check endpoints
48+ app . get ( "/health" , ( req , res ) => res . status ( 200 ) . type ( "text/plain" ) . send ( "OK" ) ) ;
49+ app . get ( "/ping" , ( req , res ) => res . status ( 200 ) . send ( "pong" ) ) ;
7050}
7151
7252/**
@@ -126,14 +106,8 @@ export function createExpressServer(options: ExpressServerOptions): {
126106} {
127107 const app = express ( ) ;
128108
129- // Set up middleware
130- setupCORS ( app ) ;
131-
132- // Parse JSON requests
133- app . use ( express . json ( ) ) ;
134-
135- // Set up common endpoints
136- setupCommonEndpoints ( app ) ;
109+ // Set up all middleware and endpoints
110+ setupMiddleware ( app ) ;
137111
138112 // Error handling middleware
139113 app . use ( ( error : Error , req : Request , res : Response , next : NextFunction ) => {
@@ -142,9 +116,7 @@ export function createExpressServer(options: ExpressServerOptions): {
142116 } ) ;
143117
144118 // Create HTTP server
145- const httpServer = app . listen ( options . port , ( ) => {
146- // This will be called when start() is invoked
147- } ) ;
119+ const httpServer = app . listen ( options . port ) ;
148120
149121 // Set up cleanup handlers
150122 setupCleanupHandlers ( httpServer , options . cleanup ) ;
0 commit comments