Skip to content

Commit 6803982

Browse files
committed
docs: update README.md for server
1 parent c57f4dd commit 6803982

File tree

1 file changed

+215
-0
lines changed

1 file changed

+215
-0
lines changed

README.md

Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -928,6 +928,221 @@ registerControllers(router, [ExampleController]);
928928
- All parameter decorators (`@Query`, `@Param`, etc.) are optional and can be used in any order.
929929
- `registerControllers(router, controllers)` will register all routes and apply middlewares, hooks, status codes, and headers as defined.
930930

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

9331148
Import only what you need:

0 commit comments

Comments
 (0)