/* eslint-disable @typescript-eslint/no-var-requires */ import type { Request, Response, NextFunction } from 'express'; process.env.TZ = "Etc/GMT"; console.log("Loading ketr.ketran"); const express = require("express"); const bodyParser = require("body-parser"); const config = require("config"); const session = require('express-session'); const basePath = require("../basepath"); const cookieParser = require("cookie-parser"); const fs = require('fs'); const app = express(); const server = require("http").createServer(app); app.use(cookieParser()); const ws = require('express-ws')(app, server); require("../console-line.js"); /* Monkey-patch console.log with line numbers */ const frontendPath = config.get("frontendPath").replace(/\/$/, "") + "/", serverConfig = config.get("server"); console.log("Hosting server from: " + basePath); let userDB: any, gameDB: any; app.use((req, res, next) => { console.log(`${req.method} ${req.url}`); next(); }); app.use(bodyParser.json()); /* App is behind an nginx proxy which we trust, so use the remote address * set in the headers */ app.set("trust proxy", true); app.set("basePath", basePath); app.use(basePath, require("../routes/basepath.js")); /* Handle static files first so excessive logging doesn't occur */ app.use(basePath, express.static(frontendPath, { index: false })); const index = require("../routes/index"); if (config.has("admin")) { const admin = config.get("admin"); app.set("admin", admin); } app.use(`${basePath}api/v1/games`, require("../routes/games")); /* Allow loading of the app w/out being logged in */ app.use(basePath, index); /* /games loads the default index */ app.use(basePath + "games", index); /* Declare the "catch all" index route last; the final route is a 404 dynamic router */ app.use(basePath, index); /** * Create HTTP server and listen for new connections */ app.set("port", serverConfig.port); process.on('SIGINT', () => { console.log("Gracefully shutting down from SIGINT (Ctrl-C) in 2 seconds"); setTimeout(() => process.exit(-1), 2000); server.close(() => process.exit(1)); }); require("../db/games").then(function(db: any) { gameDB = db; }).then(function() { return require("../db/users").then(function(db: any) { userDB = db; }); }).then(function() { console.log("DB connected. Opening server."); server.listen(serverConfig.port, () => { console.log(`http/ws server listening on ${serverConfig.port}`); }); }).catch(function(error: any) { console.error(error); process.exit(-1); }); server.on("error", function(error: any) { if (error.syscall !== "listen") { throw error; } // handle specific listen errors with friendly messages switch (error.code) { case "EACCES": console.error(serverConfig.port + " requires elevated privileges"); process.exit(1); break; case "EADDRINUSE": console.error(serverConfig.port + " is already in use"); process.exit(1); break; default: throw error; } }); module.exports = { app, server };