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

68 lines
1.5 KiB
TypeScript
Raw Normal View History

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