11c548616f9202787e6356cd1fd67ca6275982c1
[src/app-framework-demo.git] / afm-client / app / Backend / server.js
1 var config  = require('../etc/_Config');
2 var trace   = require('../etc/_Trace');
3 var RestAPI = require('./RestApis/_all');
4 var fs      = require('fs');
5
6 var express        = require('express');
7 var session        = require('express-session');
8 var bodyParser     = require('body-parser');
9 var methodOverride = require('method-override');
10
11 // instanciate express HTTP server
12 var app = express();
13
14 // chose dev or prod rootdir
15 var staticdir = 'dist.dev';
16 if (process.env.MODE) staticdir = process.env.MODE === 'prod' ? 'dist.prod' : 'dist.dev';
17 else staticdir = config.MODE === 'prod' ? 'dist.prod' : 'dist.dev';
18
19 var rootdir = __dirname + '/../../' + staticdir;
20 if (!fs.existsSync(rootdir)) {
21     console.log("### HOOPS Rootdir not found rootdir=%s\n", rootdir);
22     process.exit();
23 }
24
25 // get all data/stuff of the body (POST) parameters
26 app.use(bodyParser.json()); // parse application/json
27 app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
28
29 // This handle should contain enough for application logic
30 var serverHandle = {
31   app  :  app,           // Express server
32   config: config,
33   trace:  config.DBG_LVL > 0 ? trace : function(){/*empty function */}
34 };
35
36 // set the static files location /public/img will be /img for users
37 app.use(express.static(rootdir)); 
38
39 // Load Mock APIs
40 var apirest = new RestAPI(serverHandle);
41
42 app.get(config.URLBASE, function (req, res) {
43     console.log ("Angular OPA %s", req.originalUrl);
44     res.sendfile(config.URLBASE +"index.html", {root: rootdir});
45 });
46
47 // rewrite requested URL to include Angular hashPrompt and set session flag for RestAPI
48 app.get(config.URLBASE + '*', function(req, res) {
49     // Warning redirect should be under exact "/opa/#!page" or a redirect to home will be done
50     var redirect=config.URLBASE + '#!' + req.originalUrl.substring(config.URLBASE.length);
51     res.redirect(redirect);
52     console.log ("Redirect to: ", redirect);
53 });
54
55
56 // start app ===============================================
57 app.listen(config.EXPRESS_PORT, config.EXPRESS_HOST);
58 console.log('Server Listening http://%s:%d (rootdir=%s)', config.EXPRESS_HOST, config.EXPRESS_PORT, rootdir);