import * as express from 'express'; import { ConfigurationHelper, conf } from "./helpers/ConfigHelper"; import { DatabaseHelper } from "./helpers/DatabaseHelper"; import { Routes, RouteType } from './controllers/Routes'; import { RequestHandler } from './entities/RequestHandler'; import * as fileUpload from 'express-fileupload'; import * as expressWs from 'express-ws'; import * as ws from 'ws'; /** * Main project script * * @author Pierre HUBERT */ console.info("Comunic API v6\t@author Pierre HUBERT\t2019-" + new Date().getFullYear()); async function init() { const confFile = process.argv.length < 3 ? "config.json" : process.argv[2]; console.info("Load configuration from "+confFile+"..."); ConfigurationHelper.loadConf(confFile); console.info("Connect to database"); await DatabaseHelper.connect(); // Start HTTP Server const app = expressWs(express()).app; app.use(express.urlencoded({extended: true})); app.use(fileUpload()); // Check if the server is running behing a proxy if(conf().proxy) { console.info("Running behind proxy: " + conf().proxy); app.set("trust proxy", conf().proxy); } // Process the list of routes Routes.forEach(route => { // Callback is common to all requests type const cb = async (req : express.Request, res : express.Response)=> { const handler = new RequestHandler(req, res); try { // Check API tokens await handler.checkAPITokens(); // Check user tokens await handler.checkUserTokens(route.needLogin); const cb = route.cb(handler); if(cb) await cb; } catch(e) { console.error(e); handler.error(500, "Internal error.", false); } }; // WebSocket callback const wsCB = async (ws: ws, req: express.Request) => { try { await route.wsCallback(req, ws); } catch(e) { console.error(e); } } // Call the appropriate function switch(route.type) { case RouteType.GET: app.get(route.path, cb); break; case RouteType.WS: app.ws(route.path, wsCB); break; default: app.post(route.path, cb); break; } }) app.listen(conf().port, () => { console.info("Started server on http://127.0.0.1:" + conf().port); }); } init();