codenuk_backend_mine/services/git-integration/src/app.js
2025-10-06 15:12:49 +05:30

175 lines
4.8 KiB
JavaScript

const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const session = require('express-session');
const morgan = require('morgan');
// Import database (uses environment variables from docker-compose.yml)
const database = require('./config/database');
// Import services
const EnhancedDiffProcessingService = require('./services/enhanced-diff-processing.service');
// Import routes
const githubRoutes = require('./routes/github-integration.routes');
const githubOAuthRoutes = require('./routes/github-oauth');
const webhookRoutes = require('./routes/webhook.routes');
const vcsRoutes = require('./routes/vcs.routes');
// Import new enhanced routes
const commitsRoutes = require('./routes/commits.routes');
const oauthProvidersRoutes = require('./routes/oauth-providers.routes');
const enhancedWebhooksRoutes = require('./routes/enhanced-webhooks.routes');
const app = express();
const PORT = process.env.PORT || 8012;
// Middleware
app.use(helmet());
app.use(cors());
app.use(morgan('combined'));
// Preserve raw body for webhook signature verification
app.use(express.json({
limit: '10mb',
verify: (req, res, buf) => {
req.rawBody = buf;
}
}));
app.use(express.urlencoded({
extended: true,
verify: (req, res, buf) => {
req.rawBody = buf;
}
}));
// Session middleware
app.use(session({
secret: process.env.SESSION_SECRET || 'git-integration-secret-key-2024',
resave: false,
saveUninitialized: false,
cookie: {
secure: false, // Set to true if using HTTPS
httpOnly: true,
maxAge: 24 * 60 * 60 * 1000 // 24 hours
}
}));
// Routes
app.use('/api/github', githubRoutes);
app.use('/api/github', githubOAuthRoutes);
app.use('/api/github', webhookRoutes);
app.use('/api/vcs', vcsRoutes);
// Enhanced routes
app.use('/api/commits', commitsRoutes);
app.use('/api/oauth', oauthProvidersRoutes);
app.use('/api/webhooks', enhancedWebhooksRoutes);
// Health check endpoint
app.get('/health', (req, res) => {
res.status(200).json({
status: 'healthy',
service: 'git-integration',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
version: '1.0.0'
});
});
// API health check endpoint for gateway compatibility
app.get('/api/github/health', (req, res) => {
res.status(200).json({
status: 'healthy',
service: 'git-integration',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
version: '1.0.0'
});
});
// Root endpoint
app.get('/', (req, res) => {
res.json({
message: 'Git Integration Service',
version: '1.0.0',
endpoints: {
health: '/health',
github: '/api/github',
oauth: '/api/github/auth',
webhook: '/api/github/webhook',
vcs: '/api/vcs/:provider',
commits: '/api/commits',
oauth_providers: '/api/oauth',
enhanced_webhooks: '/api/webhooks'
}
});
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error('Error:', err);
res.status(500).json({
success: false,
message: 'Internal server error',
error: process.env.NODE_ENV === 'development' ? err.message : 'Something went wrong'
});
});
// 404 handler
app.use('*', (req, res) => {
res.status(404).json({
success: false,
message: 'Endpoint not found'
});
});
// Graceful shutdown
process.on('SIGTERM', async () => {
console.log('SIGTERM received, shutting down gracefully');
await database.close();
process.exit(0);
});
process.on('SIGINT', async () => {
console.log('SIGINT received, shutting down gracefully');
await database.close();
process.exit(0);
});
// Initialize services
async function initializeServices() {
try {
// Initialize diff processing service
const diffProcessingService = new EnhancedDiffProcessingService();
await diffProcessingService.initialize();
// Start background diff processing if enabled
if (process.env.ENABLE_BACKGROUND_DIFF_PROCESSING !== 'false') {
const processingInterval = parseInt(process.env.DIFF_PROCESSING_INTERVAL_MS) || 30000;
diffProcessingService.startBackgroundProcessing(processingInterval);
console.log('🔄 Background diff processing started');
}
console.log('✅ All services initialized successfully');
} catch (error) {
console.error('❌ Error initializing services:', error);
}
}
// Start server
app.listen(PORT, '0.0.0.0', async () => {
console.log(`🚀 Git Integration Service running on port ${PORT}`);
console.log(`📊 Health check: http://localhost:8000/health`);
console.log(`🔗 GitHub API: http://localhost:8000/api/github`);
console.log(`📝 Commits API: http://localhost:8000/api/commits`);
console.log(`🔐 OAuth API: http://localhost:8000/api/oauth`);
console.log(`🪝 Enhanced Webhooks: http://localhost:8000/api/webhooks`);
// Initialize services after server starts
await initializeServices();
});
module.exports = app;