-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhttp.framework.express.js
executable file
·391 lines (333 loc) · 12 KB
/
http.framework.express.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
'use strict';
var _stringify = require('babel-runtime/core-js/json/stringify');
var _stringify2 = _interopRequireDefault(_stringify);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var fs = require('fs');
var path = require('path');
var _ = require('lodash');
var when = require('when');
var express = require('express');
var compress = require('compression'); // aka. express.compress
var cookieParser = require('cookie-parser'); // aka. express.cookieParser
var errorHandler = require('errorhandler'); // aka. express.errorHandler
var bodyParser = require('body-parser'); // aka. express.bodyParser
var methodOverride = require('method-override'); // aka. express.methodOverride
var morgan = require('morgan'); // aka. express.logger
var session = require('express-session'); // aka. express.session
var mime = require('mime');
//
var util = require('./util.js');
var logger = null;
module.exports = HttpFrameworkExpress;
// TODO: add https support
function HttpFrameworkExpress(options, $logger, $stats) {
this._options = _.merge({
compress: true,
urlencoded: true,
parser: {
cookies: true,
json: true
},
session: false
}, options);
if (process.env.PORT) {
this._options.port = process.env.PORT;
}
this._stats = $stats;
logger = util.logger({ name: '~Express' }, $logger);
this._app = express();
this._server = null;
}
// set/get server port
HttpFrameworkExpress.prototype.protocol = function () {
return 'http' + (this._options.credentials ? 's' : '') + ':';
};
// set/get server port
HttpFrameworkExpress.prototype.port = function (nPort) {
if (nPort) {
this._options.port = nPort;
}
return this._options.port;
};
// load all services
HttpFrameworkExpress.prototype.load = function () {
logger.group('Express HttpFramework Loading...');
// add promise wrapper
return when.promise(function (resolve, reject) {
// ------------------------------------------------
try {
this._app.set('port', this._options.port);
logger.info('Using Port', this._app.get('port'));
if (!this._options.silent) {
this._app.use(this._getExpressLogger());
}
this._app.use(methodOverride());
if (this._options.env === 'dev') {
logger.info('Enabling Error Logging');
this._app.use(errorHandler({ showStack: true, dumpExceptions: true }));
}
if (this._options.compress) {
logger.info('Enabling Compression');
this._app.use(compress());
}
if (this._options.urlencoded) {
logger.info('Enabling URL Encoding');
this._app.use(bodyParser.urlencoded({ limit: '100mb', extended: true }));
}
if (this._options.parser.cookies) {
logger.info('Enabling Cookie Parser');
this._app.use(cookieParser());
}
if (this._options.parser.json) {
logger.info('Enabling JSON support');
this._app.use(bodyParser.json({ limit: '100mb' }));
}
if (this._options.session) {
logger.info('Enabling Sessions');
var defaultSession = {
secret: util.string.random(32),
resave: false, // depends on the session store, see https://github.com/expressjs/session#resave
saveUninitialized: false, // depends on several cases, see https://github.com/expressjs/session#saveuninitialized
cookie: {
// TODO: auto enable "secure: true" only if https
path: '/',
httpOnly: true,
maxAge: 1000 * 60 * 24 // 24 hours
},
storeInst: new session.MemoryStore()
};
// if this._options.session no object then make default settings
if (!_.isObject(this._options.session)) {
this._options.session = defaultSession;
} else {
this._options.session = _.merge(defaultSession, this._options.session);
}
this._app.use(session(this._options.session));
}
resolve();
logger.groupEnd('');
} catch (err) {
reject(err);
logger.groupEnd('');
}
// ------------------------------------------------
}.bind(this));
// end promise wrapper
};
HttpFrameworkExpress.prototype.validateMethod = function (method) {
if (!this._app[method] || !_.isFunction(this._app[method])) {
logger.warn('ServiceManager: Invalid method', method);
return false;
} else {
return true;
}
};
HttpFrameworkExpress.prototype.getName = function () {
return 'express';
};
HttpFrameworkExpress.prototype.app = function () {
return this._app;
};
/*
HttpFrameworkExpress.prototype.server = function() {
return this._server;
};
*/
HttpFrameworkExpress.prototype.addMethodFunction = function (method, middlewareList, routeStr, handler) {
var validMiddlewares = [];
if (middlewareList) {
for (var i = 0; i < middlewareList.length; i++) {
// if plugin has isType, is express and has setupRoute function
// filter out all invalid plugins
if (middlewareList[i] && middlewareList[i].middleware && _.isFunction(middlewareList[i].middleware.isType) && middlewareList[i].middleware.isType('express') && _.isFunction(middlewareList[i].middleware.setupRoute)) {
validMiddlewares.push(middlewareList[i]);
} else {
// missing isType or
// is not express or
// setupRoute function
}
}
}
if (validMiddlewares && _.isArray(validMiddlewares) && validMiddlewares.length) {
// run setupRoute for each plugin
_.forEach(validMiddlewares, function (validMiddleware) {
validMiddleware.middleware.setupRoute(this._app, method, routeStr, handler, validMiddleware.options);
}.bind(this));
}
this._app[method](routeStr, handler);
};
HttpFrameworkExpress.prototype.addStaticDir = function (staticDir, staticRoute, staticOptions, staticDefaultFile) {
if (staticRoute) {
return this._app.use(staticRoute, function (req, res, orgNext) {
var next = orgNext;
if (staticDefaultFile) {
staticOptions = staticOptions || {};
staticOptions.fallthrough = false; // to allow to catch error and handle it
var requestFile = req.url;
next = function next(err) {
// could not find file
if (err.code === 'ENOENT') {
// use default
fs.readFile(staticDefaultFile, function (err, content) {
if (err) {
logger.error('Missing Default Static File - Error:', err);
} else {
var mimetype = mime.getType(staticDefaultFile);
res.writeHead(200, { 'Content-Type': mimetype });
res.end(content, 'utf-8');
}
});
} else {
logger.error('Default Static Dir - Error:', err);
}
};
}
var staticFunc = express.static(staticDir, staticOptions);
staticFunc(req, res, next);
});
} else {
return this._app.use(express.static(staticDir, staticOptions));
}
};
HttpFrameworkExpress.prototype.addStaticFile = function (staticRoute, staticFile) {
this._app.get(staticRoute, function (req, res) {
res.sendFile(path.resolve(staticFile));
});
};
HttpFrameworkExpress.prototype.addStaticFileDefault = function (staticFile) {
this._app.use(function (req, res) {
res.sendFile(path.resolve(staticFile));
});
};
HttpFrameworkExpress.prototype.addRedirect = function (from, to) {
return this._app.use(from, function (req, res) {
res.redirect(to);
});
};
// custom logging function to add 'x-forwarded-for' and defaults for missing values
HttpFrameworkExpress.prototype._getExpressLogger = function () {
morgan.token('remote-addy', function (req, res) {
if (req.headers.hasOwnProperty('x-forwarded-for')) {
return req.headers['x-forwarded-for'];
} else {
return req.connection.remoteAddress;
}
});
/*
var logFormat = ':remote-addy - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" (:response-time ms)';
return express.logger(logFormat);
*/
return morgan(function (t, req, res) {
var rTime = t['response-time'](req, res);
var contentLength = t.res(req, res, 'content-length');
var status = t.status(req, res);
var url = t.url(req, res);
return t['remote-addy'](req, res) + ' - - [' + t.date(req, res) + '] "' + t.method(req, res) + ' ' + url + ' HTTP/' + t['http-version'](req, res) + '" ' + status + ' ' + (contentLength || '-') + ' "' + (t.referrer(req, res) || '-') + '" "' + (t['user-agent'](req, res) || '-') + '" (' + rTime + ' ms)';
});
};
// inject dependency from controller function DI
HttpFrameworkExpress.prototype.buildInputs = function ($rawRequest) {
// POST - req.body
// GET - req.query
// GET - req.params
return _.pick($rawRequest, ['query', 'params', 'body']);
};
// type == "view"
// route.outContentType
// templateFunc
HttpFrameworkExpress.prototype.addWrappedMethodFunction = function (method, middlewareList, routeStr, handler) {
this.addMethodFunction(method, middlewareList, routeStr, function (req, res, next) {
var responded = false;
handler(this.buildInputs(req), req.session, req.cookies, req, res, next).then(function (output) {
// ---------------------------------------
// TODO: Custom error format, defined in config
if (responded) {
logger.warn('Already responded to request');
return;
}
responded = true;
if (!output.headers || !_.isObject(output.headers)) {
output.headers = {};
}
if (output.headers.filename) {
var mimetype = mime.getType(output.headers.filename);
if (!output.headers.hasOwnProperty('Content-type')) {
output.headers['Content-type'] = mimetype;
}
if (!output.headers.hasOwnProperty('Content-disposition')) {
output.headers['Content-disposition'] = 'attachment; filename=' + output.headers.filename;
}
}
// is not buffer and is object
if (!Buffer.isBuffer(output.data) && _.isObject(output.data)) {
// assume JSON
if (!output.headers.hasOwnProperty('Content-type')) {
output.headers['Content-Type'] = 'application/json';
}
// convert object to string
output.data = (0, _stringify2.default)(output.data);
} else if (_.isString(output.data)) {
// assume HTML
if (!output.headers.hasOwnProperty('Content-type')) {
output.headers['Content-Type'] = 'text/html';
}
} else {}
// ???
// if not code passed in, default 200
if (!output.code) {
output.code = 200;
}
// merge default content-type with headers
res.writeHead(output.code, output.headers);
if (Buffer.isBuffer(output.data)) {
res.end(output.data, 'binary');
} else {
res.end(output.data);
}
// TOOD: duplicate setHeader error with proper pipeline
// next();
});
}.bind(this));
};
/**
* Validate Inputs
* TODO: replace with lib
* @param cInput
* @param req
* @returns {Array}
* @private
*/
HttpFrameworkExpress.prototype.validateInputs = function (cInput, req) {
var errors = [];
for (var i in cInput) {
// logger.log("_validateInputs:" , i);
// check input type
if (req.hasOwnProperty(i)) {
for (var k in cInput[i]) {
// check required
if (!req[i].hasOwnProperty(k) && cInput[i][k].required) {
// missing
errors.push({ error: 'Missing ' + i + ' ' + k, type: 'missing', id: k });
}
// check type
else if (req[i].hasOwnProperty(k) && cInput[i][k].type) {
var tFuncName = 'is' + util.String.capitalize(cInput[i][k].type);
// check if lodash has type function
if (_[tFuncName]) {
// check if input passes type function
if (!_[tFuncName](req[i][k])) {
errors.push({ error: 'Invalid input ' + k + ' with value ' + req[i][k] + ', expecting type ' + i, type: 'invalid', id: k });
}
}
}
}
}
}
if (errors.length === 0) {
errors = undefined;
}
if (errors.length === 1) {
errors = errors[0];
}
return errors;
};