snake-game-cicd/server.js

76 lines
1.9 KiB
JavaScript

const express = require('express');
const helmet = require('helmet');
const compression = require('compression');
const cors = require('cors');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3003;
// Middleware
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https:"],
},
},
}));
app.use(compression());
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, 'src')));
// Health Check Endpoint
app.get('/health', (req, res) => {
res.status(200).json({
status: 'healthy',
timestamp: new Date().toISOString(),
version: process.env.npm_package_version || '1.0.0'
});
});
// API Endpoints
app.get('/api/stats', (req, res) => {
res.json({
gamesPlayed: Math.floor(Math.random() * 1000),
highScore: Math.floor(Math.random() * 500),
onlinePlayers: Math.floor(Math.random() * 50)
});
});
// Serve game
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'src', 'index.html'));
});
// Error handling
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
// 404 handler
app.use((req, res) => {
res.status(404).json({ error: 'Route not found' });
});
const server = app.listen(PORT, '0.0.0.0', () => {
console.log(`🐍 Snake Game Server running on http://0.0.0.0:${PORT}`);
console.log(`🎮 Game available at: http://localhost:${PORT}`);
console.log(`❤️ Health check: http://localhost:${PORT}/health`);
});
// Graceful shutdown
process.on('SIGTERM', () => {
console.log('🛑 SIGTERM received, shutting down gracefully...');
server.close(() => {
console.log('✅ Server closed');
process.exit(0);
});
});
module.exports = app;