-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathapp.js
More file actions
132 lines (104 loc) · 3.81 KB
/
app.js
File metadata and controls
132 lines (104 loc) · 3.81 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
require('dotenv').config();
const config = require('./config'),
cors = require('cors'),
express = require('express'),
exphbs = require('express-handlebars'),
getDayjs = require('./services/dayjs-wrapper'),
jsonStore = require('./services/json-store'),
stats = require('./services/stats'),
morgan = require('morgan'),
removeExpiredSubscriptions = require('./services/remove-expired-subscriptions'),
websocket = require('./services/websocket');
let app, hbs, server, dayjs;
console.log(`${config.appName} ${config.appVersion}`);
// Schedule cleanup tasks
function scheduleCleanupTasks() {
// Run cleanup immediately on startup
removeExpiredSubscriptions()
.then(() => console.log('Startup subscription cleanup completed'))
.catch(err => console.error('Error in startup subscription cleanup:', err));
// Run subscription cleanup every 24 hours
setInterval(async() => {
try {
console.log('Running scheduled subscription cleanup...');
await removeExpiredSubscriptions();
} catch (error) {
console.error('Error in scheduled subscription cleanup:', error);
}
}, 24 * 60 * 60 * 1000); // 24 hours in milliseconds
}
morgan.format('mydate', () => {
return new Date().toLocaleTimeString('en-US', { hour12: false, fractionalSecondDigits: 3 }).replace(/:/g, ':');
});
// Initialize dayjs at startup
async function initializeDayjs() {
dayjs = await getDayjs();
}
app = express();
app.set('trust proxy', true);
app.use(morgan('[:mydate] :method :url :status :res[content-length] - :remote-addr - :response-time ms'));
app.use(cors());
// Configure handlebars template engine to work with dayjs
hbs = exphbs.create({
helpers: {
formatDate: (datetime, format) => {
return dayjs(datetime).format(format);
}
}
});
// Configure express to use handlebars
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
// Handle static files in public directory
app.use(express.static('public', {
dotfiles: 'ignore',
maxAge: '1d'
}));
// Load controllers
app.use(require('./controllers'));
async function gracefulShutdown() {
jsonStore.shutdown();
process.exit();
}
process.on('SIGINT', gracefulShutdown);
process.on('SIGTERM', gracefulShutdown);
// Persist data before dying on an unexpected error
process.on('uncaughtException', (error) => {
console.error('Uncaught exception, flushing data store before exit:', error);
jsonStore.shutdown();
process.exit(1);
});
process.on('unhandledRejection', (reason) => {
console.error('Unhandled promise rejection, flushing data store before exit:', reason);
jsonStore.shutdown();
process.exit(1);
});
async function startServer() {
await initializeDayjs();
jsonStore.initialize(config.dataFilePath);
// Start cleanup scheduling
scheduleCleanupTasks();
// Generate stats on startup, then schedule periodic regeneration
stats.generateStats().catch(err => console.error('Error generating initial stats:', err));
stats.scheduleStatsGeneration();
server = app.listen(config.port, () => {
app.locals.host = config.domain;
app.locals.port = server.address().port;
if (app.locals.host.indexOf(':') > -1) {
app.locals.host = '[' + app.locals.host + ']';
}
// Initialize WebSocket server for /wsLog
websocket.initialize(server);
console.log(`Listening at http://${app.locals.host}:${app.locals.port}`);
})
.on('error', (error) => {
switch (error.code) {
case 'EADDRINUSE':
console.log(`Error: Port ${config.port} is already in use.`);
break;
default:
console.log(error.code);
}
});
}
startServer().catch(console.error);