-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
247 lines (180 loc) · 6.91 KB
/
app.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
var cluster = require('cluster');
var dotenv = require('dotenv');
var isDev = process.env.NODE_ENV == 'production' || process.env.NODE_ENV == 'enterprise' ? false : true;
var dotenv_path = __dirname + "/config/env/.env." + (process.env.NODE_ENV ? process.env.NODE_ENV : "development");
dotenv.config({
path: dotenv_path,
silent: true
});
if (cluster.isMaster) {
require('./queue-init')();
var clusterWorkerSize = process.env.WEB_CONCURRENCY || require('os').cpus().length;
console.log('env %s, master pid %s, total Workers: %s ', process.env.NODE_ENV,process.pid,clusterWorkerSize);
for (var i = 0; i < clusterWorkerSize; i ++) {
cluster.fork();
}
cluster.on('exit',function(worker_process) {
console.log("Worker %d died pid %d",worker_process.id,process.pid);
})
}
else {
var path = require('path');
var express = require('express');
var winston = require('winston');
var expressWinston = require('express-winston');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var MongoSessionStore = require('connect-mongo')(session);
var flash = require('connect-flash');
var passport = require('passport');
var fs = require('fs');
var cors = require('cors');
var async = require('async');
var subdomain = require('express-subdomain');
var app = express();
//job queue user interface
// if (process.env.NODE_ENV == 'production') {
// var kue = require('kue');
// var ui = require('kue-ui');
// kue.createQueue({
// redis: process.env.REDIS_URL
// })
// ui.setup({
// apiURL: '/api',
// baseURL: '/kue',
// updateInterval: 5000
// })
// app.use('/api',kue.app);
// app.use('/kui',ui.app);
// }
require('./config/setup-passport');
var userFolderPath = __dirname + "/user";
var customRoutes = __dirname + '/app/routes/custom'
var viewsToSet = [];
viewsToSet.push(__dirname + '/views');
var nunjucks = require('express-nunjucks');
app.set('view engine', 'html');
if (isDev) {
app.set('subdomain offset',3);
}
fs.readdir(userFolderPath, function (err, files) {
if (!files) {
app.set('views', viewsToSet)
nunjucks.setup({
watch: isDev,
noCache: isDev,
}, app).then(function(nunjucks_env) {
require('./nunjucks/filters')(nunjucks_env,process.env)
});
return;
}
files = files.filter(function (item) {
return !(/(^|\/)\.[^\/\.]/g).test(item);
})
async.each(files, function (file, eachCb) {
var full_path = path.join(userFolderPath, file);
var team_name = file;
fs.stat(full_path, function (err, stat) {
if (err) {
eachCb(err)
} else {
if (stat.isDirectory() && files) {
//serving the views
var view_path = path.join(userFolderPath, file + "/views");
viewsToSet.push(view_path);
app.use(subdomain(team_name,require(customRoutes)));
}
eachCb();
}
})
}, function (err) {
if (err) return winston.error("❌ cannot sync the user folder files :", err);
app.set('views', viewsToSet)
nunjucks.setup({
watch: isDev,
noCache: isDev,
}, app).then(function(nunjucks_env) {
require('./nunjucks/filters')(nunjucks_env,process.env)
});
})
})
app.use(cors());
app.use(require('serve-favicon')(__dirname + '/public/images/favicon.ico'));
app.use(express.static(path.join(__dirname, '/public')));
// Redirect https
app.use(function (req, res, next) {
if (process.env.USE_SSL === 'true' && 'https' !== req.header('x-forwarded-proto')) {
return res.redirect('https://' + req.header('host') + req.url);
}
next();
});
var routes = require('./app/routes');
app.use(bodyParser.urlencoded({extended: false})); // application/x-www-form-urlencoded
app.use(bodyParser.json()); // application/JSON
app.use(require('compression')());
app.set('trust proxy', true);
app.use(cookieParser());
var domain = 'localhost';
if (process.env.HOST) {
var urlParts = process.env.HOST.split('.');
urlParts.splice(0, urlParts.length-2);
// Remove port
urlParts[urlParts.length-1] = urlParts[urlParts.length-1].split(':')[0];
domain = '.' + urlParts.join('.');
}
// Mongo Store to prevent a warnning.
app.use(session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
cookie: {domain: domain},
store: new MongoSessionStore({
url: process.env.MONGODB_URI ? process.env.MONGODB_URI : 'mongodb://localhost/arraysdb',
// touchAfter: 240 * 3600 // time period in seconds
})
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
// Logger
app.use(expressWinston.logger({
transports: [
new winston.transports.Console({
json: false,
colorize: isDev
})
],
expressFormat: true,
meta: false
}));
//
//
var mongoose_client = require('./app/models/mongoose_client');
var raw_source_documents = require('./app/models/raw_source_documents');
var datasource_descriptions = require('./app/models/descriptions');
if (typeof process === 'object') { /* to debug promise */
process.on('unhandledRejection', function (error, promise) {
console.error("== Node detected an unhandled rejection! ==");
console.error(error);
});
}
var modelNames = [raw_source_documents.ModelName];
mongoose_client.FromApp_Init_IndexesMustBeBuiltForSchemaWithModelsNamed(modelNames)
mongoose_client.WhenMongoDBConnected(function () {
mongoose_client.WhenIndexesHaveBeenBuilt(function () {
// winston.info("💬 Proceeding to boot app. ");
//
routes.MountRoutes(app);
//
// Run actual server
if (module === require.main) {
var server = app.listen(process.env.PORT || 9080, function () {
var host = isDev ? 'localhost' : server.address().address;
var port = server.address().port;
winston.info("📡 Worker %d running pid %d listing at %s:%s",cluster.worker.id,process.pid,host,port);
});
}
});
});
}