1
0
mirror of https://gitlab.com/comunic/comunicapiv2 synced 2024-11-25 23:09:22 +00:00
comunicapiv2/src/main.ts

68 lines
1.5 KiB
TypeScript

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';
/**
* Main project script
*
* @author Pierre HUBERT
*/
console.info("Comunic API v6\t@author Pierre HUBERT\t2019-" + new Date().getFullYear());
async function init() {
console.info("Load configuration...");
ConfigurationHelper.loadConf("config.json");
console.info("Connect to database");
await DatabaseHelper.connect();
// Start HTTP Server
const app = express();
app.use(express.urlencoded({extended: true}));
app.use(fileUpload());
// 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);
}
};
if(route.type == RouteType.GET)
app.get(route.path, cb);
else
app.post(route.path, cb);
})
app.listen(conf().port, () => {
console.info("Started server on http://127.0.0.1:" + conf().port);
});
}
init();