-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
128 lines (106 loc) · 3.67 KB
/
server.js
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
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const fs = require('fs');
const crypto = require('crypto');
const readline = require('readline');
const { startPolling, stopPolling } = require('./services/pollingService');
const { initializeDatabase, updateSupportedTokens } = require('./database');
const { globalCors } = require('./security/cors'); // Import only globalCors
const { eventBusMiddleware } = require("./middleware/eventbus/express");
let SECRET_KEY = process.env.SECRET_KEY;
const app = express();
app.use(express.json());
const PORT = process.env.PORT || 4467;
app.set('trust proxy', true);
const CRYPTOCOMPARE_BASE_URL = 'https://min-api.cryptocompare.com/data';
// Helper function to prompt user input for missing secrets
const promptInput = async (query) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve) => {
rl.question(query, (answer) => {
rl.close();
resolve(answer);
});
});
};
// Check required secrets
async function ensureSecrets() {
const requiredSecrets = [
'API_KEY_CRYPTOCOMPARE',
'VUE_APP_GOOGLE_CLIENT_ID',
'VUE_APP_GOOGLE_CLIENT_SECRET',
];
let secretsUpdated = false;
for (const secret of requiredSecrets) {
if (!process.env[secret]) {
console.error(`[ERROR] Missing required environment variable: ${secret}`);
console.error(`[INFO] Please add ${secret} to your .env file.`);
process.exit(1); // Terminate gracefully if a required variable is missing
}
}
// Handle optional secrets
if (!SECRET_KEY) {
SECRET_KEY = crypto.randomBytes(64).toString('hex');
secretsUpdated = true;
}
// Update .env file if optional secrets were generated
if (secretsUpdated) {
const envContent = Object.entries({ SECRET_KEY })
.map(([key, value]) => `${key}=${value}`)
.join('\n');
fs.writeFileSync('.env', envContent, { flag: 'a' }); // Append to .env
}
}
// Initialize the app
async function initializeApp() {
await ensureSecrets(); // Validate and collect secrets
app.use(bodyParser.json());
app.use(cors(globalCors)); // Use global CORS configuration
// SSE Route via eventBusMiddleware
app.get('/events', eventBusMiddleware);
// Uncomment if rate limiting is required
/*
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per window
});
app.use(limiter);
*/
// Database initialization
initializeDatabase();
// Routes setup
const routes = require('./routes');
app.use('/api', routes);
// Start the server
app.listen(PORT, () => {
console.log(`[INFO] Server running on http://localhost:${PORT}`);
startPolling();
// Schedule daily token updates
const cron = require('node-cron');
cron.schedule('0 0 * * *', () => {
console.log('[INFO] Running daily token update...');
updateSupportedTokens();
});
// Initial token update
updateSupportedTokens();
});
// Graceful shutdown handling
process.on('SIGINT', () => {
console.log('[INFO] Shutting down server...');
stopPolling();
process.exit();
});
process.on('SIGTERM', () => {
console.log('[INFO] Shutting down server...');
stopPolling();
process.exit();
});
}
// Start the application
initializeApp();