@@ -56,6 +56,7 @@ console.log(isEmail("user@example.com")); // true
5656- [ ** URL Utilities** ] ( #-url-utilities )
5757- [ ** Validate Utilities** ] ( #-validate-utilities )
5858- [ ** Decorators Utilities** ] ( #-decorators-utilities )
59+ - [ ** Express Server** ] ( #-express-server )
5960
6061---
6162
@@ -928,6 +929,221 @@ registerControllers(router, [ExampleController]);
928929- All parameter decorators (` @Query ` , ` @Param ` , etc.) are optional and can be used in any order.
929930- ` registerControllers(router, controllers) ` will register all routes and apply middlewares, hooks, status codes, and headers as defined.
930931
932+ ## 🚀 Express Server
933+
934+ A production-ready Express server with enterprise-grade features for building robust web services and APIs.
935+
936+ ### Features
937+
938+ - ** Security** : CORS, Helmet, rate limiting, timeouts, body size limits
939+ - ** Monitoring** : Request logging, Prometheus metrics, health checks
940+ - ** Performance** : Response compression, static file serving, conditional settings
941+ - ** Reliability** : Graceful shutdown, connection tracking, error handling
942+ - ** Developer UX** : OpenAPI docs, debugging tools
943+ - ** Extensibility** : Lifecycle hooks, middleware registration, custom routes
944+
945+ ### Getting Started
946+
947+ Create a server with the fluent builder pattern:
948+
949+ ``` ts
950+ import { ServerConfigBuilder , ExpressServer } from " @catbee/utils" ;
951+
952+ // Configure the server
953+ const config = new ServerConfigBuilder ()
954+ .withPort (3000 )
955+ .withHost (' localhost' )
956+ .enableCors ()
957+ .enableHelmet ()
958+ .enableCompression ()
959+ .withGlobalPrefix (' /api' )
960+ .withRequestLogging ({
961+ enable: true ,
962+ ignorePaths: [' /healthz' , ' /metrics' ]
963+ })
964+ .enableMetrics ()
965+ .build ();
966+
967+ // Create and start the server
968+ const server = new ExpressServer (config , {
969+ beforeStart : (app ) => console .log (' Server about to start...' ),
970+ afterStart : (server ) => console .log (' Server started successfully!' )
971+ });
972+
973+ // Register health checks
974+ server .registerHealthCheck (' database' , async () => {
975+ return await checkDatabaseConnection ();
976+ });
977+
978+ // Register routes
979+ const router = server .createRouter (' /users' );
980+ router .get (' /' , (req , res ) => {
981+ res .json ({ users: [] });
982+ });
983+
984+ // Start the server
985+ await server .start ();
986+
987+ // Enable graceful shutdown handling
988+ server .enableGracefulShutdown ();
989+ ```
990+
991+ ### Server Configuration Builder
992+
993+ Use the fluent builder API to configure all aspects of your server:
994+
995+ ``` ts
996+ import { ServerConfigBuilder } from " @catbee/utils" ;
997+
998+ const config = new ServerConfigBuilder ()
999+ // Basic configuration
1000+ .withPort (3000 ) // Set listen port
1001+ .withHost (' 0.0.0.0' ) // Set listen address
1002+ .withGlobalPrefix (' /api/v1' ) // Set global route prefix
1003+
1004+ // Security
1005+ .enableCors () // Enable CORS (simple)
1006+ .withCors ({ // Configure CORS (advanced)
1007+ origin: [' https://example.com' ],
1008+ methods: [' GET' , ' POST' ]
1009+ })
1010+ .enableHelmet () // Enable secure headers
1011+ .enableRateLimit ({ // Configure rate limiting
1012+ max: 100 ,
1013+ windowMs: 15 * 60 * 1000
1014+ })
1015+
1016+ // Performance
1017+ .enableCompression () // Enable response compression
1018+ .withStaticFolder ({ // Serve static files
1019+ path: ' /assets' ,
1020+ directory: ' ./public/assets' ,
1021+ maxAge: ' 1d'
1022+ })
1023+
1024+ // Monitoring
1025+ .enableMetrics ({ // Enable Prometheus metrics
1026+ path: ' /metrics'
1027+ })
1028+ .withHealthCheck ({ // Configure health checks
1029+ path: ' /health' ,
1030+ detailed: true
1031+ })
1032+ .enableResponseTime () // Track response times
1033+ .enableRequestLogging () // Log requests
1034+
1035+ // Documentation
1036+ .enableOpenApi (' ./openapi.yaml' , { // Enable OpenAPI docs
1037+ mountPath: ' /docs'
1038+ })
1039+
1040+ // Microservice configuration
1041+ .withMicroService ({ // Configure as microservice
1042+ appName: ' user-service' ,
1043+ serviceVersion: {
1044+ enable: true ,
1045+ version: ' 1.0.0'
1046+ }
1047+ })
1048+
1049+ // Build final configuration
1050+ .build ();
1051+ ```
1052+
1053+ ### Server Lifecycle Hooks
1054+
1055+ Register hooks for key server lifecycle events:
1056+
1057+ ``` ts
1058+ const server = new ExpressServer (config , {
1059+ // Before server initialization (middleware setup)
1060+ beforeInit : (server ) => {
1061+ console .log (' Initializing server...' );
1062+ },
1063+
1064+ // After server initialization (routes registered)
1065+ afterInit : (server ) => {
1066+ console .log (' Server initialized' );
1067+ },
1068+
1069+ // Before server starts listening
1070+ beforeStart : (app ) => {
1071+ console .log (' Starting server...' );
1072+ },
1073+
1074+ // After server has started listening
1075+ afterStart : (httpServer ) => {
1076+ console .log (' Server started' );
1077+ },
1078+
1079+ // Before server begins shutdown
1080+ beforeStop : (httpServer ) => {
1081+ console .log (' Shutting down server...' );
1082+ },
1083+
1084+ // After server has fully stopped
1085+ afterStop : () => {
1086+ console .log (' Server stopped' );
1087+ },
1088+
1089+ // Global request handler
1090+ onRequest : (req , res , next ) => {
1091+ console .log (' Processing request...' );
1092+ next ();
1093+ },
1094+
1095+ // Global response handler
1096+ onResponse : (req , res , next ) => {
1097+ res .setHeader (' X-Server-Time' , new Date ().toISOString ());
1098+ next ();
1099+ },
1100+
1101+ // Global error handler
1102+ onError : (err , req , res , next ) => {
1103+ console .error (' Error processing request:' , err );
1104+ res .status (500 ).json ({ error: ' Something went wrong' });
1105+ }
1106+ });
1107+ ```
1108+
1109+ ### Health Checks
1110+
1111+ Register health checks for monitoring service dependencies:
1112+
1113+ ``` ts
1114+ // Simple health check
1115+ server .registerHealthCheck (' storage' , () => {
1116+ return fs .existsSync (' ./data' );
1117+ });
1118+
1119+ // Async health check
1120+ server .registerHealthCheck (' database' , async () => {
1121+ try {
1122+ await db .ping ();
1123+ return true ;
1124+ } catch (err ) {
1125+ return false ;
1126+ }
1127+ });
1128+ ```
1129+
1130+ ### Graceful Shutdown
1131+
1132+ Enable zero-downtime deployments with graceful shutdown:
1133+
1134+ ``` ts
1135+ // Enable graceful shutdown handling
1136+ server .enableGracefulShutdown ();
1137+
1138+ // Manually trigger a graceful shutdown
1139+ async function shutdown() {
1140+ console .log (' Starting graceful shutdown...' );
1141+ await server .stop ();
1142+ console .log (' Server stopped gracefully' );
1143+ process .exit (0 );
1144+ }
1145+ ```
1146+
9311147## 🏁 Usage
9321148
9331149Import only what you need:
0 commit comments