|
|
const express = require('express');
|
|
|
const cors = require('cors');
|
|
|
const helmet = require('helmet');
|
|
|
const morgan = require('morgan');
|
|
|
const http = require('http');
|
|
|
const socketIo = require('socket.io');
|
|
|
require('dotenv').config();
|
|
|
|
|
|
const connectDB = require('./config/database');
|
|
|
const authRoutes = require('./routes/auth');
|
|
|
const chatRoutes = require('./routes/chat');
|
|
|
const conversationRoutes = require('./routes/conversations');
|
|
|
const { initializeSocket } = require('./services/socketService');
|
|
|
const rateLimitMiddleware = require('./middleware/rateLimit');
|
|
|
|
|
|
|
|
|
connectDB();
|
|
|
|
|
|
const app = express();
|
|
|
const server = http.createServer(app);
|
|
|
const io = socketIo(server, {
|
|
|
cors: {
|
|
|
origin: process.env.CORS_ORIGIN || "http://localhost:3000",
|
|
|
methods: ["GET", "POST"]
|
|
|
}
|
|
|
});
|
|
|
|
|
|
|
|
|
initializeSocket(io);
|
|
|
|
|
|
|
|
|
app.use(helmet());
|
|
|
app.use(cors({
|
|
|
origin: process.env.CORS_ORIGIN || "http://localhost:3000",
|
|
|
credentials: true
|
|
|
}));
|
|
|
app.use(morgan('combined'));
|
|
|
app.use(express.json({ limit: '10mb' }));
|
|
|
app.use(express.urlencoded({ extended: true }));
|
|
|
app.use(rateLimitMiddleware);
|
|
|
|
|
|
|
|
|
app.use('/api/auth', authRoutes);
|
|
|
app.use('/api/chat', chatRoutes);
|
|
|
app.use('/api/conversations', conversationRoutes);
|
|
|
|
|
|
|
|
|
app.get('/api/health', (req, res) => {
|
|
|
res.json({ status: 'OK', timestamp: new Date().toISOString() });
|
|
|
});
|
|
|
|
|
|
|
|
|
app.use((err, req, res, next) => {
|
|
|
console.error(err.stack);
|
|
|
res.status(500).json({
|
|
|
error: 'Something went wrong!',
|
|
|
message: process.env.NODE_ENV === 'development' ? err.message : 'Internal server error'
|
|
|
});
|
|
|
});
|
|
|
|
|
|
|
|
|
app.use('*', (req, res) => {
|
|
|
res.status(404).json({ error: 'Route not found' });
|
|
|
});
|
|
|
|
|
|
const PORT = process.env.PORT || 5000;
|
|
|
|
|
|
server.listen(PORT, () => {
|
|
|
console.log(`🚀 Server running on port ${PORT}`);
|
|
|
console.log(`📱 Environment: ${process.env.NODE_ENV}`);
|
|
|
});
|
|
|
|
|
|
module.exports = { app, server }; |