1
0
mirror of https://gitlab.com/comunic/comunicapiv2 synced 2025-02-16 22:22:39 +00:00
comunicapiv2/src/main.ts

65 lines
1.4 KiB
TypeScript
Raw Normal View History

2019-11-21 18:06:50 +01:00
import * as express from 'express';
import { ConfigurationHelper, conf } from "./helpers/ConfigHelper";
2019-11-21 17:35:56 +01:00
import { DatabaseHelper } from "./helpers/DatabaseHelper";
2019-11-21 18:06:50 +01:00
import { Routes, RouteType } from './controllers/Routes';
2019-11-22 08:50:15 +01:00
import { RequestHandler } from './entities/RequestHandler';
2019-11-21 16:28:48 +01:00
2019-11-21 16:08:52 +01:00
/**
* Main project script
*
* @author Pierre HUBERT
*/
2019-11-21 16:28:48 +01:00
console.info("Comunic API v6\t@author Pierre HUBERT\t2019-" + new Date().getFullYear());
2019-11-21 16:08:52 +01:00
2019-11-21 17:37:30 +01:00
async function init() {
console.info("Load configuration...");
ConfigurationHelper.loadConf("config.json");
2019-11-21 17:35:56 +01:00
2019-11-21 17:37:30 +01:00
console.info("Connect to database");
await DatabaseHelper.connect();
2019-11-21 18:06:50 +01:00
// Start HTTP Server
const app = express();
2019-11-22 09:30:34 +01:00
app.use(express.urlencoded({extended: true}));
2019-11-22 08:50:15 +01:00
2019-11-21 18:06:50 +01:00
// Process the list of routes
Routes.forEach(route => {
2019-11-22 08:50:15 +01:00
// Callback is common to all requests type
const cb = async (req : express.Request, res : express.Response)=> {
const handler = new RequestHandler(req, res);
2019-11-23 13:24:24 +01:00
try {
2019-11-22 08:50:15 +01:00
2019-11-23 13:24:24 +01:00
// Check API tokens
await handler.checkAPITokens();
2019-11-22 08:50:15 +01:00
2019-11-23 13:47:06 +01:00
// Check user tokens
await handler.checkUserTokens(route.needLogin);
2019-11-23 13:24:24 +01:00
const cb = route.cb(handler);
if(cb)
await cb;
} catch(e) {
console.error(e);
2019-11-30 12:18:45 +01:00
handler.error(500, "Internal error.", false);
2019-11-23 13:24:24 +01:00
}
2019-11-21 18:26:19 +01:00
};
2019-11-21 18:06:50 +01:00
if(route.type == RouteType.GET)
2019-11-21 18:26:19 +01:00
app.get(route.path, cb);
else
app.post(route.path, cb);
2019-11-21 18:06:50 +01:00
})
app.listen(conf().port, () => {
console.info("Started server on http://127.0.0.1:" + conf().port);
});
2019-11-21 17:37:30 +01:00
}
init();