mirror of
https://gitlab.com/comunic/comunicapiv2
synced 2025-02-16 22:22:39 +00:00
95 lines
1.9 KiB
TypeScript
95 lines
1.9 KiB
TypeScript
import * as express from 'express';
|
|
import { conf } from "./helpers/ConfigHelper";
|
|
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 Comunic server
|
|
*
|
|
* @author Pierre Hubert
|
|
*/
|
|
|
|
/**
|
|
* Run the server
|
|
*/
|
|
export async function startServer() {
|
|
// 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);
|
|
|
|
// Send a response to the server, if it has not
|
|
// been done yet
|
|
if(!handler.sentResponse)
|
|
res.status(500).send({
|
|
error: {
|
|
code: 500,
|
|
message: "Internal error"
|
|
}
|
|
})
|
|
}
|
|
};
|
|
|
|
// 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);
|
|
});
|
|
} |