-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
73 lines (58 loc) · 1.79 KB
/
server.js
File metadata and controls
73 lines (58 loc) · 1.79 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
/**
* Server entry point
* Initializes database and starts the application
*/
require('dotenv').config();
const { sequelize, testConnection, syncDatabase } = require('./src/config/db');
const { closeConnection: closeRabbitConnection } = require('./src/config/rabbitmq');
const { startLeaveRequestConsumer } = require('./src/queues/leaveRequestProcessor');
const logger = require('./src/utils/logger');
// Import models to ensure they're registered
require('./src/models');
let server;
/**
* Initialize and start server
*/
const startServer = async () => {
try {
logger.info('Testing database connection...');
await testConnection();
logger.info('Synchronizing database...');
await syncDatabase({ alter: true });
logger.info('Database is ready!');
const app = require('./src/app');
const PORT = parseInt(process.env.PORT, 10) || 3000;
server = app.listen(PORT, () => {
logger.info(`Server running on port ${PORT}`);
});
try {
await startLeaveRequestConsumer();
} catch (consumerError) {
logger.error('Failed to start leave request consumer', consumerError);
}
} catch (error) {
logger.error('Failed to start server:', error);
process.exit(1);
}
};
const shutdown = async (signal) => {
try {
logger.info(`${signal} received, shutting down gracefully...`);
if (server) {
await new Promise((resolve, reject) => {
server.close((err) => (err ? reject(err) : resolve()));
});
}
await Promise.allSettled([
sequelize.close(),
closeRabbitConnection?.()
]);
process.exit(0);
} catch (error) {
logger.error('Error during shutdown', error);
process.exit(1);
}
};
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('SIGTERM', () => shutdown('SIGTERM'));
startServer();