Utilizziamo i cookie per migliorare la tua esperienza sul sito
CodeWorlds

Production Best Practices - zasady prawdziwego centuriona

doświadczony dowódco! Konsul Caesar.js zebrał dla Ciebie najważniejsze zasady prowadzenia rzymskich legionów na polach produkcji. To kodeks prawdziwego centuriona, który gwarantuje, że Twoje oddziały będą działać niezawodnie i wydajnie przez wszystkie kampanie!

Production Best Practices to zbiór sprawdzonych metod i zasad, które zapewniają niezawodność, bezpieczeństwo i wydajność aplikacji w środowisku produkcyjnym.

Bezpieczeństwo - ochrona przed barbarzyńcami

1// Helmet - ochrona przed atakami
2import helmet from 'helmet';
3
4app.use(helmet({
5 contentSecurityPolicy: {
6 directives: {
7 defaultSrc: ["'self'"],
8 styleSrc: ["'self'", "'unsafe-inline'"],
9 scriptSrc: ["'self'"],
10 imgSrc: ["'self'", "data:", "https:"],
11 },
12 },
13 hsts: {
14 maxAge: 31536000,
15 includeSubDomains: true,
16 preload: true
17 }
18}));
19
20// Rate limiting
21import rateLimit from 'express-rate-limit';
22
23app.use(rateLimit({
24 windowMs: 15 * 60 * 1000, // 15 minut
25 max: 100, // max 100 żądań na IP
26 message: 'Zbyt wiele żądań z tego IP!',
27 standardHeaders: true,
28 legacyHeaders: false,
29}));
30
31// CORS policy
32app.enableCors({
33 origin: process.env.ALLOWED_ORIGINS?.split(',') || [],
34 credentials: true,
35 methods: ['GET', 'POST', 'PUT', 'DELETE'],
36 allowedHeaders: ['Content-Type', 'Authorization'],
37});

Monitoring - obserwacja prowincji

1// Health checks
2@Controller('health')
3export class HealthController {
4 @Get()
5 @HealthCheck()
6 check() {
7 return this.health.check([
8 () => this.db.pingCheck('database'),
9 () => this.memory.checkHeap('memory_heap', 150 * 1024 * 1024),
10 () => this.redis.pingCheck('redis'),
11 ]);
12 }
13}
14
15// Metrics collection
16@Injectable()
17export class MetricsService {
18 private registry = new prometheus.Registry();
19 
20 constructor() {
21 // Default metrics
22 prometheus.collectDefaultMetrics({
23 register: this.registry,
24 prefix: 'legionariusze_legion_',
25 });
26 
27 // Custom metrics
28 this.httpDuration = new prometheus.Histogram({
29 name: 'http_request_duration_seconds',
30 help: 'Duration of HTTP requests in seconds',
31 labelNames: ['method', 'route', 'status'],
32 registers: [this.registry],
33 });
34 }
35}

Error Handling - ochrona przed zatonięciem

1// Global exception filter
2@Catch()
3export class GlobalExceptionFilter implements ExceptionFilter {
4 catch(exception: unknown, host: ArgumentsHost) {
5 const ctx = host.switchToHttp();
6 const response = ctx.getResponse();
7 const request = ctx.getRequest();
8 
9 let status = HttpStatus.INTERNAL_SERVER_ERROR;
10 let message = 'Internal server error';
11 
12 if (exception instanceof HttpException) {
13 status = exception.getStatus();
14 message = exception.getResponse();
15 }
16 
17 // Log error
18 this.logger.error({
19 statusCode: status,
20 timestamp: new Date().toISOString(),
21 path: request.url,
22 method: request.method,
23 error: exception,
24 });
25 
26 // Return sanitized error
27 response.status(status).json({
28 statusCode: status,
29 timestamp: new Date().toISOString(),
30 path: request.url,
31 message: process.env.NODE_ENV === 'production' 
32 ? 'Something went wrong' 
33 : message,
34 });
35 }
36}

Graceful Shutdown - bezpieczne dokowanie

1// main.ts
2async function bootstrap() {
3 const app = await NestFactory.create(AppModule);
4 
5 // Graceful shutdown
6 process.on('SIGTERM', async () => {
7 console.log('SIGTERM received, shutting down gracefully');
8 await app.close();
9 process.exit(0);
10 });
11 
12 process.on('SIGINT', async () => {
13 console.log('SIGINT received, shutting down gracefully');
14 await app.close();
15 process.exit(0);
16 });
17 
18 await app.listen(3000);
19}
Vai a CodeWorlds