-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
194 lines (156 loc) · 5.38 KB
/
server.js
File metadata and controls
194 lines (156 loc) · 5.38 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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
/**
* Local Storage API - Main Server
*
* A sophisticated Node.js web API for file storage with S3-like functionality.
* Features:
* - File upload, download, and deletion
* - Chunked uploads for large files
* - MySQL database for metadata storage
* - JWT-based authentication
* - Rate limiting and security headers
* - CORS support
*
* @author Local Storage API
* @version 1.0.0
*/
const express = require('express');
const path = require('path');
require('dotenv').config();
// Import configuration
const config = require('./config/app');
const { testConnection, syncDatabase } = require('./config/database');
// Import middleware
const {
corsMiddleware,
helmetMiddleware,
apiLimiter,
sanitizeRequest,
notFoundHandler,
errorHandler
} = require('./middleware');
// Import routes
const routes = require('./routes');
// Create Express application
const app = express();
// ===========================================
// MIDDLEWARE CONFIGURATION
// ===========================================
// Trust proxy (for rate limiting behind reverse proxy)
app.set('trust proxy', 1);
// Security headers with Helmet
app.use(helmetMiddleware);
// CORS configuration
app.use(corsMiddleware);
// Parse JSON bodies
app.use(express.json({ limit: '10mb' }));
// Parse URL-encoded bodies
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
// Sanitize request data
app.use(sanitizeRequest);
// Apply rate limiting to all API routes
app.use('/api', apiLimiter);
// ===========================================
// ROUTES
// ===========================================
// Mount API routes
app.use('/api', routes);
// Serve static files from uploads directory (for public files)
// Note: This is optional and should be secured in production
if (config.server.env === 'development') {
app.use('/uploads', express.static(path.resolve(config.upload.dir)));
}
// Root endpoint
app.get('/', (req, res) => {
res.json({
success: true,
message: 'Welcome to Local Storage API',
version: '1.0.0',
documentation: '/api',
health: '/api/health'
});
});
// ===========================================
// ERROR HANDLING
// ===========================================
// Handle 404 - Route not found
app.use(notFoundHandler);
// Global error handler
app.use(errorHandler);
// ===========================================
// SERVER STARTUP
// ===========================================
/**
* Initialize and start the server
*/
const startServer = async () => {
try {
console.log('🚀 Starting Local Storage API...');
console.log(`📍 Environment: ${config.server.env}`);
// Test database connection
console.log('🔌 Connecting to database...');
const dbConnected = await testConnection();
if (!dbConnected) {
console.error('❌ Failed to connect to database. Please check your configuration.');
console.log('💡 Make sure MySQL is running and the database exists.');
console.log('💡 You can create the database with: CREATE DATABASE local_storage_api;');
process.exit(1);
}
// Sync database models
console.log('📊 Synchronizing database models...');
await syncDatabase({ alter: config.server.env === 'development' });
// Ensure upload directories exist
const { ensureUploadDirs } = require('./services/uploadService');
await ensureUploadDirs();
console.log('📁 Upload directories ready');
// Start HTTP server
const server = app.listen(config.server.port, config.server.host, () => {
console.log('');
console.log('='.repeat(50));
console.log('✅ Local Storage API is running!');
console.log('='.repeat(50));
console.log(`🌐 URL: http://${config.server.host}:${config.server.port}`);
console.log(`📚 API Docs: http://${config.server.host}:${config.server.port}/api`);
console.log(`❤️ Health: http://${config.server.host}:${config.server.port}/api/health`);
console.log('='.repeat(50));
console.log('');
});
// Graceful shutdown handling
const gracefulShutdown = async (signal) => {
console.log(`\n📴 Received ${signal}. Shutting down gracefully...`);
server.close(async () => {
console.log('🔌 HTTP server closed');
// Close database connection
const { sequelize } = require('./config/database');
await sequelize.close();
console.log('🔌 Database connection closed');
console.log('👋 Goodbye!');
process.exit(0);
});
// Force close after 10 seconds
setTimeout(() => {
console.error('⚠️ Could not close connections in time, forcefully shutting down');
process.exit(1);
}, 10000);
};
// Listen for termination signals
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
// Handle uncaught exceptions
process.on('uncaughtException', (error) => {
console.error('❌ Uncaught Exception:', error);
process.exit(1);
});
// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
console.error('❌ Unhandled Rejection at:', promise, 'reason:', reason);
process.exit(1);
});
} catch (error) {
console.error('❌ Failed to start server:', error);
process.exit(1);
}
};
// Start the server
startServer();
// Export app for testing
module.exports = app;