UNPKG

6.77 kBJavaScriptView Raw
1var express = require('express');
2var path = require('path');
3var favicon = require('serve-favicon');
4var logger = require('morgan');
5var cookieParser = require('cookie-parser');
6var bodyParser = require('body-parser');
7var MongoClient = require('mongodb').MongoClient;
8var handlebars = require('express-handlebars');
9var nconf = require('nconf');
10var session = require('express-session');
11var async = require('async');
12
13// routes
14var routes = require('./routes/index');
15
16var app = express();
17
18// setup the translation
19var i18n = new (require('i18n-2'))({
20 locales: ['en', 'de']
21});
22
23// view engine setup
24app.set('views', path.join(__dirname, 'views'));
25app.engine('hbs', handlebars({ extname: 'hbs', defaultLayout: 'layout.hbs' }));
26app.set('view engine', 'hbs');
27
28// helpers for the handlebars templating platform
29handlebars = handlebars.create({
30 helpers: {
31 __ : function(value) {
32 return i18n.__(value);
33 },
34 toJSON : function(object) {
35 return JSON.stringify(object);
36 },
37 niceBool : function(object) {
38 if(object === undefined){
39 return "No";
40 }
41 if(object === true){
42 return "Yes";
43 }else{
44 return "No";
45 }
46 },
47 app_context : function(){
48 if(nconf.stores.app.get('app:context') != undefined){
49 return "/" + nconf.stores.app.get('app:context');
50 }else{
51 return "";
52 }
53 },
54 formatBytes : function(bytes) {
55 if(bytes == 0) return '0 Byte';
56 var k = 1000;
57 var decimals = 2;
58 var dm = decimals + 1 || 3;
59 var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
60 var i = Math.floor(Math.log(bytes) / Math.log(k));
61 return (bytes / Math.pow(k, i)).toPrecision(dm) + ' ' + sizes[i];
62 }
63 }
64});
65
66// setup nconf to read in the file
67// create config dir and blank files if they dont exist
68var fs = require('fs');
69if (!fs.existsSync("config")){
70 fs.mkdirSync("config");
71}
72if (!fs.existsSync("config/config.json")){
73 fs.writeFileSync("config/config.json", "{}");
74}
75if (!fs.existsSync("config/app.json")){
76 fs.writeFileSync("config/app.json", "{}");
77}
78
79var connection_config = path.join(__dirname, 'config', 'config.json');
80var app_config = path.join(__dirname, 'config', 'app.json');
81
82// if config files exist but are blank we write blank files for nconf
83if (fs.existsSync(app_config, "utf8")) {
84 if(fs.readFileSync(app_config, "utf8") == ""){
85 fs.writeFileSync(app_config, "{}", 'utf8');
86 }
87}
88if (fs.existsSync(connection_config, "utf8")) {
89 if(fs.readFileSync(connection_config, "utf8") == ""){
90 fs.writeFileSync(connection_config, "{}", 'utf8');
91 }
92}
93
94// setup the two conf. 'app' holds application config, and connections
95// holds the mongoDB connections
96nconf.add('connections', { type: 'file', file: connection_config });
97nconf.add('app', { type: 'file', file: app_config });
98
99// set app defaults
100var app_host = '0.0.0.0';
101var app_port = process.env.PORT || 1234;
102
103// get the app configs and override if present
104if(nconf.stores.app.get('app:host') != undefined){
105 app_host = nconf.stores.app.get('app:host');
106}
107if(nconf.stores.app.get('app:port') != undefined){
108 app_port = nconf.stores.app.get('app:port');
109}
110if(nconf.stores.app.get('app:locale') != undefined){
111 i18n.setLocale(nconf.stores.app.get('app:locale'));
112}
113
114// setup the app context
115app_context = "";
116if(nconf.stores.app.get('app:context') != undefined){
117 app_context = "/" + nconf.stores.app.get('app:context');
118}
119
120app.use(logger('dev'));
121app.use(bodyParser.json({limit: '16mb'}));
122app.use(bodyParser.urlencoded({extended: false }));
123app.use(cookieParser());
124
125// setup session
126app.use(session({
127 secret: '858SGTUyX8w1L6JNm1m93Cvm8uX1QX2D',
128 resave: true,
129 saveUninitialized: true
130}))
131
132// front-end modules loaded from NPM
133app.use(app_context + '/ace', express.static(path.join(__dirname, 'node_modules/ace-builds/src-min/')));
134app.use(app_context + '/font-awesome', express.static(path.join(__dirname, 'node_modules/font-awesome/')));
135app.use(app_context + '/jquery', express.static(path.join(__dirname, 'node_modules/jquery/dist/')));
136app.use(app_context + '/bootstrap', express.static(path.join(__dirname, 'node_modules/bootstrap/dist/')));
137app.use(app_context + '/css',express.static(path.join(__dirname, 'public/css')));
138app.use(app_context + '/fonts',express.static(path.join(__dirname, 'public/fonts')));
139app.use(app_context + '/js',express.static(path.join(__dirname, 'public/js')));
140app.use(app_context + '/favicon.ico',express.static(path.join(__dirname, 'public/favicon.ico')));
141
142// Make stuff accessible to our router
143app.use(function (req, res, next) {
144 req.nconf = nconf.stores;
145 req.handlebars = handlebars;
146 req.i18n = i18n;
147 req.app_context = app_context;
148 next();
149});
150
151// add context to route if required
152if(app_context != ""){
153 app.use(app_context, routes);
154}else{
155 app.use('/', routes);
156}
157
158// catch 404 and forward to error handler
159app.use(function (req, res, next) {
160 var err = new Error('Not Found');
161 err.status = 404;
162 next(err);
163});
164
165// error handlers
166
167// development error handler
168// will print stacktrace
169if (app.get('env') === 'development') {
170 app.use(function (err, req, res, next) {
171 res.status(err.status || 500);
172 res.render('error', {
173 message: err.message,
174 error: err,
175 helpers: handlebars.helpers
176 });
177 });
178}
179
180// production error handler
181// no stacktraces leaked to user
182app.use(function (err, req, res, next) {
183 res.status(err.status || 500);
184 res.render('error', {
185 message: err.message,
186 error: {},
187 helpers: handlebars.helpers
188 });
189});
190
191// add the connections to the connection pool
192var connection_list = nconf.stores.connections.get('connections');
193var connPool = require('./connections');
194app.locals.dbConnections = null;
195
196async.forEachOf(connection_list, function (value, key, callback) {
197 var MongoURI = require('mongo-uri');
198
199 try {
200 uri = MongoURI.parse(value.connection_string);
201 connPool.addConnection({connName: key, connString: value.connection_string}, app, function(err, data){
202 if(err){
203 delete connection_list[key];
204 }
205 callback();
206 });
207 } catch (err) {
208 callback();
209 }
210}, function (err) {
211if (err) console.error(err.message);
212 // lift the app
213 app.listen(app_port, app_host, function () {
214 console.log('adminMongo listening on host: http://' + app_host + ':' + app_port + app_context);
215 });
216});
217
218module.exports = app;