-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
62 lines (55 loc) · 2.58 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const cache = {}, config = {};
global.cache = cache;
global.config = config;
const express = require("express");
const bodyParser = require('body-parser');
const http = require('http');
const fs = require('fs');
const apiFunctions = require('./api');
const NodeCache = require("node-cache");
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
const initApp = async () => {
const functionTag = 'initApp';
console.log(`${functionTag}: Booting up the app`);
try {
const config = JSON.parse(fs.readFileSync('config.json'));
if (config) console.log(`${functionTag}: Configurations loaded successfully from config.json`);
global.config = config;
const expressPort = process.env.PORT || config.express.port;
if (!expressPort) throw new Error(`Cannot boot the app due to unspecified port`);
/**
* Associate functions with the router
*/
const functions = Object.keys(apiFunctions);
if (!functions || !(functions.length > 0)) throw new Error(`Unable to associate api routes with functions`);
global.cache = new NodeCache(config.cache);
console.log(`${functionTag}: Initialised Cache Service`);
const app = express();
app.use(bodyParser.json());
app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
config.routes.forEach(r => {
if (!r.method) throw new Error(`Undefined HTTP Method for routing: ${JSON.stringify(r)}`);
if (!r.route) throw new Error(`Undefined route for routing: ${JSON.stringify(r)}`);
if (!r.function) throw new Error(`Undefined function mapping for routing: ${JSON.stringify(r)}`);
switch (r.method) {
case "GET":
app.get(r.route, apiFunctions[r.function]);
break;
case "POST":
app.post(r.route, apiFunctions[r.function]);
break;
default:
throw new Error(`Unimplemented HTTP method (${r.method}) encountered`);
}
console.log(`${functionTag}: Binding route [${r.method} ${r.route}] with function: ${r.function}`);
});
let server = http.createServer(app).listen(expressPort, () => {
console.log(`${functionTag}: Api Initialised on port ${expressPort}`);
});
server.setTimeout(3600);
} catch (error) {
console.log(`${functionTag}: An unexpected error occured - ${JSON.stringify(error, Object.getOwnPropertyNames(error))}`);
}
};
initApp();