-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
159 lines (131 loc) · 4.05 KB
/
Copy pathserver.js
File metadata and controls
159 lines (131 loc) · 4.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const http = require('http');
const socketIo = require('socket.io');
require('dotenv').config();
const { testConnection } = require('./config/database');
// Import routes
const authRoutes = require('./routes/auth');
const productRoutes = require('./routes/products');
const inventoryRoutes = require('./routes/inventory');
const orderRoutes = require('./routes/orders');
const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
cors: {
origin: process.env.CLIENT_URL || "http://localhost:3000",
methods: ["GET", "POST"]
}
});
// Security middleware
app.use(helmet());
// Rate limiting
const limiter = rateLimit({
windowMs: 1 * 60 * 1000, // 1 minute
max: 1000, // limit each IP to 1000 requests per minute (much more generous for development)
message: 'Too many requests from this IP, please try again later.'
});
app.use('/api/', limiter);
// CORS configuration
app.use(cors({
origin: process.env.CLIENT_URL || "http://localhost:3000",
credentials: true
}));
// Body parsing middleware
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
// Static files
app.use('/uploads', express.static('uploads'));
// Health check endpoint
app.get('/health', (req, res) => {
res.json({
status: 'OK',
timestamp: new Date().toISOString(),
uptime: process.uptime()
});
});
// API routes
app.use('/api/auth', authRoutes);
app.use('/api/products', productRoutes);
app.use('/api/inventory', inventoryRoutes);
app.use('/api/orders', orderRoutes);
// Socket.IO for real-time features
io.on('connection', (socket) => {
console.log('User connected:', socket.id);
// Join user to their personal room
socket.on('join-user-room', (userId) => {
socket.join(`user-${userId}`);
console.log(`User ${userId} joined their room`);
});
// Handle order status updates
socket.on('order-status-update', (data) => {
const { orderId, status, userId } = data;
// Notify both buyer and seller about order status change
socket.to(`user-${userId}`).emit('order-updated', {
orderId,
status,
timestamp: new Date().toISOString()
});
});
// Handle new order notifications
socket.on('new-order', (data) => {
const { sellerId, orderId } = data;
// Notify seller about new order
socket.to(`user-${sellerId}`).emit('new-order-notification', {
orderId,
timestamp: new Date().toISOString()
});
});
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
});
});
// Make io accessible to routes
app.set('io', io);
// Error handling middleware
app.use((err, req, res, next) => {
console.error('Error:', err);
if (err.type === 'entity.parse.failed') {
return res.status(400).json({ message: 'Invalid JSON format' });
}
res.status(500).json({
message: 'Internal server error',
...(process.env.NODE_ENV === 'development' && { error: err.message })
});
});
// 404 handler
app.use('*', (req, res) => {
res.status(404).json({ message: 'Route not found' });
});
const PORT = process.env.PORT || 5000;
// Start server
const startServer = async () => {
try {
// Test database connection
await testConnection();
server.listen(PORT, () => {
console.log(`🚀 Server running on port ${PORT}`);
console.log(`📊 Health check: http://localhost:${PORT}/health`);
console.log(`🌍 Environment: ${process.env.NODE_ENV || 'development'}`);
});
} catch (error) {
console.error('Failed to start server:', error);
process.exit(1);
}
};
// Handle graceful shutdown
process.on('SIGTERM', () => {
console.log('SIGTERM received. Shutting down gracefully...');
server.close(() => {
console.log('Process terminated');
});
});
process.on('SIGINT', () => {
console.log('SIGINT received. Shutting down gracefully...');
server.close(() => {
console.log('Process terminated');
});
});
startServer();