Fix GameModel.cleanDb()
[vchess.git] / server / bin / www
... / ...
CommitLineData
1#!/usr/bin/env node
2
3/**
4 * Module dependencies.
5 */
6
7let app = require('../app');
8const debug = require('debug')('vc:server');
9const http = require('http');
10
11/**
12 * Get port from environment and store in Express.
13 */
14
15const port = normalizePort(process.env.PORT || '3000');
16app.set('port', port);
17
18/**
19 * Create HTTP server.
20 */
21
22let server = http.createServer(app);
23
24/*
25 * CRON tasks
26 */
27
28let cron = require('node-cron');
29const UserModel = require("../models/User");
30const GameModel = require("../models/Game");
31cron.schedule('0 0 0 * * *', function() {
32 // Remove unlogged users and unstarted games every 24h
33 UserModel.cleanUsersDb();
34 GameModel.cleanGamesDb();
35});
36
37/**
38 * Listen on provided port, on all network interfaces.
39 */
40
41server.listen(port);
42server.on('error', onError);
43server.on('listening', onListening);
44
45/*
46 * Sockets handling
47 */
48
49const WebSocket = require('ws');
50const wss = new WebSocket.Server({ server: server });
51require('../sockets')(wss);
52
53/**
54 * Normalize a port into a number, string, or false.
55 */
56
57function normalizePort(val) {
58 const parsedPort = parseInt(val, 10);
59
60 if (isNaN(parsedPort)) {
61 // named pipe
62 return val;
63 }
64
65 if (parsedPort >= 0) {
66 // port number
67 return parsedPort;
68 }
69
70 return false;
71}
72
73/**
74 * Event listener for HTTP server "error" event.
75 */
76
77function onError(error) {
78 if (error.syscall !== 'listen') {
79 throw error;
80 }
81
82 const bind = typeof port === 'string'
83 ? 'Pipe ' + port
84 : 'Port ' + port;
85
86 // handle specific listen errors with friendly messages
87 switch (error.code) {
88 case 'EACCES':
89 console.error(bind + ' requires elevated privileges');
90 process.exit(1);
91 break;
92 case 'EADDRINUSE':
93 console.error(bind + ' is already in use');
94 process.exit(1);
95 break;
96 default:
97 throw error;
98 }
99}
100
101/**
102 * Event listener for HTTP server "listening" event.
103 */
104
105function onListening() {
106 const addr = server.address();
107 const bind = typeof addr === 'string'
108 ? 'pipe ' + addr
109 : 'port ' + addr.port;
110 debug('Listening on ' + bind);
111}