-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
1419 lines (1350 loc) · 48.6 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
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @themost-framework 2.0 Codename Blueshift Copyright (c) 2017-2025, THEMOST LP All rights reserved
var HttpError = require('@themost/common').HttpError;
var HttpServerError = require('@themost/common').HttpServerError;
var HttpNotFoundError = require('@themost/common').HttpNotFoundError;
var Args = require('@themost/common').Args;
var TraceUtils = require('@themost/common').TraceUtils;
var _ = require('lodash');
var mvc = require('./mvc');
var LangUtils = require('@themost/common').LangUtils;
var path = require("path");
var fs = require("fs");
var ejs = require('ejs');
var url = require('url');
var http = require('http');
var SequentialEventEmitter = require('@themost/common').SequentialEventEmitter;
var DataConfigurationStrategy = require('@themost/data').DataConfigurationStrategy;
var querystring = require('querystring');
var crypto = require('crypto');
var Symbol = require('symbol');
var HttpHandler = require('./types').HttpHandler;
var AuthStrategy = require('./handlers/auth').AuthStrategy;
var DefaultAuthStrategy = require('./handlers/auth').DefaultAuthStrategy;
var EncryptionStrategy = require('./handlers/auth').EncryptionStrategy;
var DefaultEncryptionStrategy = require('./handlers/auth').DefaultEncryptionStrategy;
var CacheStrategy = require('./cache').CacheStrategy;
var DefaultCacheStrategy = require('./cache').DefaultCacheStrategy;
var LocalizationStrategy = require('./localization').LocalizationStrategy;
var DefaultLocalizationStrategy = require('./localization').DefaultLocalizationStrategy;
var HttpConfiguration = require('./config').HttpConfiguration;
var HttpApplicationService = require('./types').HttpApplicationService;
var HttpContext = require('./context').HttpContext;
var StaticHandler = require('./handlers/static').StaticHandler;
var executionPathProperty = Symbol('executionPath');
var configPathProperty = Symbol('configPath');
var configProperty = Symbol('config');
var currentProperty = Symbol('current');
var servicesProperty = Symbol('services');
var DEFAULT_HTML_ERROR = fs.readFileSync(path.resolve(__dirname, 'http-error.html.ejs'), 'utf8');
/**
* @classdesc ApplicationOptions class describes the startup options of a MOST Web Framework application.
* @class
* @constructor
* @property {number} port - The HTTP binding port number.
* The default value is either PORT environment variable or 3000.
* @property {string} bind - The HTTP binding ip address or hostname.
* The default value is either IP environment variable or 127.0.0.1.
* @property {number|string} cluster - A number which represents the number of clustered applications.
* The default value is zero (no clustering). If cluster is 'auto' then the number of clustered applications
* depends on hardware capabilities (number of CPUs).
@example
//load module
var web = require("most-web");
//start server
web.current.start({ port:80, bind:"0.0.0.0",cluster:'auto' });
@example
//Environment variables already set: IP=198.51.100.0 PORT=80
var web = require("most-web");
web.current.start();
*/
// eslint-disable-next-line no-unused-vars
function ApplicationOptions() {
}
/**
* Abstract class that represents a data context
* @constructor
*/
function HttpDataContext() {
//
}
/**
* @returns {*}
*/
HttpDataContext.prototype.db = function () {
return null;
};
/**
* @param {string} name
* @returns {DataModel}
*/
// eslint-disable-next-line no-unused-vars
HttpDataContext.prototype.model = function (name) {
return null;
};
/**
* @param {string} type
* @returns {*}
*/
// eslint-disable-next-line no-unused-vars
HttpDataContext.prototype.dataTypes = function (type) {
return null;
};
/**
*
* @param {HttpApplication} app
* @constructor
*/
function HttpContextProvider(app) {
HttpContextProvider.super_.bind(this)(app);
}
LangUtils.inherits(HttpContextProvider,HttpApplicationService);
/**
* @returns {HttpContext}
*/
HttpContextProvider.prototype.create = function(req,res) {
var context = new HttpContext(req,res);
//set context application
context.application = this.getApplication();
return context;
};
/**
* @class
* @constructor
* @param {string=} executionPath
* @augments SequentialEventEmitter
*/
function HttpApplication(executionPath) {
//Sets the current execution path
this[executionPathProperty] = _.isNil(executionPath) ? path.join(process.cwd()) : path.resolve(executionPath);
//Gets the current application configuration path
this[configPathProperty] = _.isNil(executionPath) ? path.join(process.cwd(), 'config') : path.resolve(executionPath, 'config');
//initialize services
this[servicesProperty] = { };
//set configuration
this[configProperty] = new HttpConfiguration(this[configPathProperty]);
/**
* Gets or sets a collection of application handlers
* @type {Array}
*/
this.handlers = [];
var self = this;
//initialize handlers collection
var configurationHandlers = this.getConfiguration().handlers;
var defaultHandlers = require('./resources/app.json').handlers;
for (var i = 0; i < defaultHandlers.length; i++) {
(function(item) {
if (typeof configurationHandlers.filter(function(x) { return x.name === item.name; })[0] === 'undefined') {
configurationHandlers.push(item);
}
})(defaultHandlers[i]);
}
var reModule = /^@themost\/web\//i;
_.forEach(configurationHandlers, function (handlerConfiguration) {
try {
var handlerPath = handlerConfiguration.type;
if (reModule.test(handlerPath)) {
handlerPath = handlerPath.replace(reModule,'./');
}
else if (/^\//.test(handlerPath)) {
handlerPath = self.mapPath(handlerPath);
}
var handlerModule = require(handlerPath), handler = null;
if (handlerModule) {
//if module exports a constructor
if (typeof handlerModule === 'function') {
self.handlers.push(new handlerModule());
}
//else if module exports a method called createInstance()
else if (typeof handlerModule.createInstance === 'function') {
//call createInstance
handler = handlerModule.createInstance();
if (handler) {
self.handlers.push(handler);
}
}
else {
TraceUtils.log('The specified handler (%s) cannot be instantiated. The module does not export a class constructor or createInstance() function.', handlerConfiguration.name);
}
}
}
catch (err) {
throw new Error('The specified handler ' + handlerConfiguration.name + ' cannot be loaded.' + err.message);
}
});
//set default context provider
self.useService(HttpContextProvider);
//set authentication strategy
self.useStrategy(AuthStrategy, DefaultAuthStrategy);
//set cache strategy
self.useStrategy(CacheStrategy, DefaultCacheStrategy);
//set encryption strategy
self.useStrategy(EncryptionStrategy, DefaultEncryptionStrategy);
//set localization strategy
self.useStrategy(LocalizationStrategy, DefaultLocalizationStrategy);
//set authentication strategy
self.getConfiguration().useStrategy(DataConfigurationStrategy, DataConfigurationStrategy);
/**
* Gets or sets a boolean that indicates whether the application is in development mode
* @type {boolean}
*/
this.development = (process.env.NODE_ENV === 'development');
/**
*
* @type {{html, text, json, unauthorized}|*}
*/
this.errors = httpApplicationErrors(this);
}
LangUtils.inherits(HttpApplication, SequentialEventEmitter);
/**
* @returns {HttpApplication}
*/
HttpApplication.getCurrent = function() {
if (typeof HttpApplication[currentProperty] === 'object') {
return HttpApplication[currentProperty];
}
HttpApplication[currentProperty] = new HttpApplication();
return HttpApplication[currentProperty];
};
/**
* @returns {HttpConfiguration}
*/
HttpApplication.prototype.getConfiguration = function() {
return this[configProperty];
};
/**
* @returns {EncryptionStrategy}
*/
HttpApplication.prototype.getEncryptionStrategy = function() {
return this.getStrategy(EncryptionStrategy);
};
/**
* @returns {AuthStrategy}
*/
HttpApplication.prototype.getAuthStrategy = function() {
return this.getStrategy(AuthStrategy);
};
/**
* @returns {LocalizationStrategy}
*/
HttpApplication.prototype.getLocalizationStrategy = function() {
return this.getStrategy(LocalizationStrategy);
};
HttpApplication.prototype.getExecutionPath = function() {
return this[executionPathProperty];
};
/**
* Resolves the given path
* @param {string} arg
*/
HttpApplication.prototype.mapExecutionPath = function(arg) {
Args.check(_.isString(arg),'Path must be a string');
return path.resolve(this.getExecutionPath(), arg);
};
/**
* Sets static content root directory
* @param {string} rootDir
*/
HttpApplication.prototype.useStaticContent = function(rootDir) {
/**
* @type {StaticHandler}
*/
var staticHandler = _.find(this.handlers, function(x) {
return x.constructor === StaticHandler;
});
if (typeof staticHandler === 'undefined') {
throw new Error('An instance of StaticHandler class cannot be found in application handlers');
}
staticHandler.rootDir = rootDir;
return this;
};
HttpApplication.prototype.getConfigurationPath = function() {
return this[configPathProperty];
};
/**
* Initializes application configuration.
* @return {HttpApplication}
*/
HttpApplication.prototype.init = function () {
//initialize basic directives collection
var directives = require("./angular/directives");
directives.apply(this);
return this;
};
/**
* Returns the path of a physical file based on a given URL.
* @param {string} s
*/
HttpApplication.prototype.mapPath = function (s) {
var uri = url.parse(s).pathname;
return path.join(this[executionPathProperty], uri);
};
/**
* Converts an application URL into one that is usable on the requesting client. A valid application relative URL always start with "~/".
* If the relativeUrl parameter contains an absolute URL, the URL is returned unchanged.
* Note: An HTTP application base path may be set in settings/app/base configuration section. The default value is "/".
* @param {string} appRelativeUrl - A string which represents an application relative URL like ~/login
*/
HttpApplication.prototype.resolveUrl = function (appRelativeUrl) {
if (/^~\//.test(appRelativeUrl)) {
var base = this.getConfiguration().getSourceAt("settings/app/base") || "/";
base += /\/$/.test(base) ? '' : '/';
return appRelativeUrl.replace(/^~\//, base);
}
return appRelativeUrl;
};
/**
* Resolves ETag header for the given file. If the specified does not exist or is invalid returns null.
* @param {string=} file - A string that represents the file we want to query
* @param {function(Error,string=)} callback
*/
HttpApplication.prototype.resolveETag = function(file, callback) {
fs.exists(file, function(exists) {
try {
if (exists) {
fs.stat(file, function(err, stats) {
if (err) {
callback(err);
}
else {
if (!stats.isFile()) {
callback(null);
}
else {
//validate if-none-match
var md5 = crypto.createHash('md5');
md5.update(stats.mtime.toString());
var result = md5.digest('base64');
callback(null, result);
}
}
});
}
else {
callback(null);
}
}
catch (e) {
callback(null);
}
});
};
// noinspection JSUnusedGlobalSymbols
/**
* @param {HttpContext} context
* @param {string} executionPath
* @param {function(Error, Boolean)} callback
*/
HttpApplication.prototype.unmodifiedRequest = function(context, executionPath, callback) {
try {
var requestETag = context.request.headers['if-none-match'];
if (typeof requestETag === 'undefined' || requestETag == null) {
callback(null, false);
return;
}
HttpApplication.prototype.resolveETag(executionPath, function(err, result) {
callback(null, (requestETag===result));
});
}
catch (err) {
TraceUtils.error(err);
callback(null, false);
}
};
/**
* @param request {string|IncomingMessage}
* @returns {*}
* */
HttpApplication.prototype.resolveMime = function (request) {
var extensionName;
if (typeof request=== 'string') {
//get file extension
extensionName = path.extname(request);
}
else if (typeof request=== 'object') {
//get file extension
extensionName = path.extname(request.url);
}
else {
return;
}
return _.find(this.getConfiguration().mimes, function(x) {
return (x.extension === extensionName);
});
};
/**
*
* @param {HttpContext} context
* @param {Function} callback
*/
HttpApplication.prototype.processRequest = function (context, callback) {
var self = this;
if (typeof context === 'undefined' || context == null) {
callback.call(self);
}
else {
//1. beginRequest
context.emit('beginRequest', context, function (err) {
if (err) {
callback.call(context, err);
}
else {
//2. validateRequest
context.emit('validateRequest', context, function (err) {
if (err) {
callback.call(context, err);
}
else {
//3. authenticateRequest
context.emit('authenticateRequest', context, function (err) {
if (err) {
callback.call(context, err);
}
else {
//4. authorizeRequest
context.emit('authorizeRequest', context, function (err) {
if (err) {
callback.call(context, err);
}
else {
//5. mapRequest
context.emit('mapRequest', context, function (err) {
if (err) {
callback.call(context, err);
}
else {
//5b. postMapRequest
context.emit('postMapRequest', context, function(err) {
if (err) {
callback.call(context, err);
}
else {
//process HEAD request
if (context.request.method==='HEAD') {
//7. endRequest
context.emit('endRequest', context, function (err) {
callback.call(context, err);
});
}
else {
//6. processRequest
if (context.request.currentHandler != null)
context.request.currentHandler.processRequest(context, function (err) {
if (err) {
callback.call(context, err);
}
else {
//7. endRequest
context.emit('endRequest', context, function (err) {
callback.call(context, err);
});
}
});
else {
var er = new HttpNotFoundError();
if (context.request && context.request.url) {
er.resource = context.request.url;
}
callback.call(context, er);
}
}
}
});
}
});
}
});
}
});
}
});
}
});
}
};
/**
* Gets the default data context based on the current configuration
* @returns {*}
*/
HttpApplication.prototype.db = function () {
var config = this.getConfiguration();
if ((config.adapters === null) || (config.adapters.length === 0))
throw new Error('Data adapters configuration settings are missing or cannot be accessed.');
var adapter = null;
if (config.adapters.length === 1) {
//there is only one adapter so try to instantiate it
adapter = config.adapters[0];
}
else {
adapter = _.find(config.adapters,function (x) {
return x.default;
});
}
if (adapter === null)
throw new Error('There is no default data adapter or the configuration is incorrect.');
//try to instantiate adapter
if (!adapter.invariantName)
throw new Error('The default data adapter has no invariant name.');
var adapterType = config.adapterTypes[adapter.invariantName];
if (adapterType == null)
throw new Error('The default data adapter type cannot be found.');
if (typeof adapterType.createInstance === 'function') {
return adapterType.createInstance(adapter.options);
}
else if (adapterType.require) {
var m = require(adapterType.require);
if (typeof m.createInstance === 'function') {
return m.createInstance(adapter.options);
}
throw new Error('The default data adapter cannot be instantiated. The module provided does not export a function called createInstance().')
}
};
/**
* @returns {HttpContextProvider}
*/
HttpApplication.prototype.getContextProvider = function() {
return this.getService(HttpContextProvider);
};
/**
* Creates an instance of HttpContext class.
* @param {ClientRequest} request
* @param {ServerResponse} response
* @returns {HttpContext}
*/
HttpApplication.prototype.createContext = function (request, response) {
var context = this.getContextProvider().create(request, response);
//set context application
context.application = this;
//set handler events
for (var i = 0; i < HttpHandler.Events.length; i++) {
var eventName = HttpHandler.Events[i];
for (var j = 0; j < this.handlers.length; j++) {
var handler = this.handlers[j];
if (typeof handler[eventName] === 'function') {
context.on(eventName, handler[eventName].bind(handler));
}
}
}
return context;
};
/**
* @param {*} options
* @param {*} data
* @param {Function} callback
*/
HttpApplication.prototype.executeExternalRequest = function(options,data, callback) {
//make request
var https = require('https'),
opts = (typeof options==='string') ? url.parse(options) : options,
httpModule = (opts.protocol === 'https:') ? https : http;
var req = httpModule.request(opts, function(res) {
res.setEncoding('utf8');
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function(){
var result = {
statusCode: res.statusCode,
headers: res.headers,
body:data,
encoding:'utf8'
};
/**
* destroy sockets (manually close an unused socket) ?
*/
callback(null, result);
});
});
req.on('error', function(e) {
//return error
callback(e);
});
if(data)
{
if (typeof data ==="object" )
req.write(JSON.stringify(data));
else
req.write(data.toString());
}
req.end();
};
/**
* Executes an internal process
* @param {Function(HttpContext)} fn
*/
HttpApplication.prototype.execute = function (fn) {
var request = createRequestInternal.call(this);
fn.call(this, this.createContext(request, createResponseInternal.call(this,request)));
};
/**
* Executes an unattended internal process
* @param {Function} fn
*/
HttpApplication.prototype.unattended = function (fn) {
//create context
var request = createRequestInternal.call(this), context = this.createContext(request, createResponseInternal.call(this,request));
//get unattended account
var account = this.getAuthStrategy().getUnattendedExecutionAccount();
//set unattended execution account
if (typeof account !== 'undefined' || account!==null) {
context.user = { name: account, authenticationType: 'Basic'};
}
//execute internal process
fn.call(this, context);
};
/**
* Load application extension
*/
HttpApplication.prototype.extend = function (extension) {
if (typeof extension === 'undefined')
{
//register all application extensions
var extensionFolder = this.mapPath('/extensions');
if (fs.existsSync(extensionFolder)) {
var arr = fs.readdirSync(extensionFolder);
for (var i = 0; i < arr.length; i++) {
if (path.extname(arr[i])==='.js')
require(path.join(extensionFolder, arr[i]));
}
}
}
else {
//register the specified extension
if (typeof extension === 'string') {
var extensionPath = this.mapPath('/extensions/' + extension + '.js');
if (fs.existsSync(extensionPath)) {
//load extension
require(extensionPath);
}
}
}
return this;
};
/**
*
* @param {*|string} options
* @param {Function} callback
*/
HttpApplication.prototype.executeRequest = function (options, callback) {
var opts = { };
if (typeof options === 'string') {
_.assign(opts, { url:options });
}
else {
_.assign(opts, options);
}
var request = createRequestInternal.call(this,opts),
response = createResponseInternal.call(this,request);
if (!opts.url) {
callback(new Error('Internal request url cannot be empty at this context.'));
return;
}
if (opts.url.indexOf('/') !== 0)
{
var uri = url.parse(opts.url);
opts.host = uri.host;
opts.hostname = uri.hostname;
opts.path = uri.path;
opts.port = uri.port;
//execute external request
this.executeExternalRequest(opts,null, callback);
}
else {
//todo::set cookie header (for internal requests)
/*
IMPORTANT: set response Content-Length to -1 in order to force the default HTTP response format.
if the content length is unknown (server response does not have this header)
in earlier version of node.js <0.11.9 the response contains by default a hexadecimal number that
represents the content length. This number appears exactly after response headers and before response body.
If the content length is defined the operation omits this hexadecimal value
e.g. the wrong or custom formatted response
HTTP 1.1 Status OK
Content-Type: text/html
...
Connection: keep-alive
6b8
<html><body>
...
</body></html>
e.g. the standard format
HTTP 1.1 Status OK
Content-Type: text/html
...
Connection: keep-alive
<html><body>
...
</body></html>
*/
response.setHeader('Content-Length',-1);
handleRequestInternal.call(this, request, response, function(err) {
if (err) {
callback(err);
}
else {
try {
//get statusCode
var statusCode = response.statusCode;
//get headers
var headers = {};
if (response._header) {
var arr = response._header.split('\r\n');
for (var i = 0; i < arr.length; i++) {
var header = arr[i];
if (header) {
var k = header.indexOf(':');
if (k>0) {
headers[header.substr(0,k)] = header.substr(k+1);
}
}
}
}
//get body
var body = null;
var encoding = null;
if (_.isArray(response.output)) {
if (response.output.length>0) {
body = response.output[0].substr(response._header.length);
encoding = response.outputEncodings[0];
}
}
//build result (something like ServerResponse)
var result = {
statusCode: statusCode,
headers: headers,
body:body,
encoding:encoding
};
callback(null, result);
}
catch (e) {
callback(e);
}
}
});
}
};
/**
* @private
* @this HttpApplication
* @param {ClientRequest} request
* @param {ServerResponse} response
* @param callback
*/
function handleRequestInternal(request, response, callback)
{
var self = this, context = self.createContext(request, response);
//add query string
if (request.url.indexOf('?') > 0)
_.assign(context.params, querystring.parse(request.url.substring(request.url.indexOf('?') + 1)));
//add form
if (request.form)
_.assign(context.params, request.form);
//add files
if (request.files)
_.assign(context.params, request.files);
self.processRequest(context, function (err) {
if (err) {
if (self.listeners('error').length === 0) {
onError.bind(self)(context, err, function () {
response.end();
callback();
});
}
else {
//raise application error event
self.emit('error', { context:context, error:err } , function () {
response.end();
callback();
});
}
}
else {
context.finalize(function() {
response.end();
callback();
});
}
});
}
/**
* @private
* @param {*} options
*/
function createRequestInternal(options) {
var opt = options ? options : {};
var request = new http.IncomingMessage();
request.method = (opt.method) ? opt.method : 'GET';
request.url = (opt.url) ? opt.url : '/';
request.httpVersion = '1.1';
request.headers = (opt.headers) ? opt.headers : {
host: 'localhost',
'user-agent': 'Mozilla/5.0 (X11; Linux i686; rv:10.0) Gecko/20100101 Firefox/22.0',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'accept-language': 'en,en-US;q=0.5',
'accept-encoding': 'gzip, deflate',
connection: 'keep-alive',
'cache-control': 'max-age=0' };
if (opt.cookie)
request.headers.cookie = opt.cookie;
request.cookies = (opt.cookies) ? opt.cookies : {};
request.session = (opt.session) ? opt.session : {};
request.params = (opt.params) ? opt.params : {};
request.query = (opt.query) ? opt.query : {};
request.form = (opt.form) ? opt.form : {};
request.body = (opt.body) ? opt.body : {};
request.files = (opt.files) ? opt.files : {};
return request;
}
/**
* Creates a mock-up server response
* @param {ClientRequest} req
* @returns {ServerResponse|*}
* @private
*/
function createResponseInternal(req) {
return new http.ServerResponse(req);
}
/**
*
* @param {HttpContext} context
* @param {Error|*} err
* @param {function(Error=)} callback
* @private
*/
function onHtmlError(context, err, callback) {
try {
if (context == null) {
return callback(err);
}
// get request and response
var request = context.request;
var response = context.response;
// validate request
if ((request == null) || (response == null)) {
return callback(err);
}
//HTML custom errors
var str;
if (err instanceof HttpError) {
str = ejs.render(DEFAULT_HTML_ERROR, {
model:err,
html: {
resolveUrl: context.resolveUrl.bind(context)
}
});
}
else {
// convert error to http error
var finalErr = new HttpError(500, null, err.message);
finalErr.stack = err.stack;
str = ejs.render(DEFAULT_HTML_ERROR, {
model: finalErr,
html: {
resolveUrl: context.resolveUrl.bind(context)
}
});
}
//write status header
response.writeHead(err.statusCode || 500 , { "Content-Type": "text/html" });
response.write(str);
response.end();
return callback();
}
catch (err) {
//log process error
TraceUtils.error(err);
//and continue execution
callback(err);
}
}
/**
* @private
* @this HttpApplication
* @param {HttpContext} context
* @param {Error|*} err
* @param {Function} callback
*/
function onError(context, err, callback) {
callback = callback || function () { };
try {
if (err == null) {
return callback();
}
// log request
if (context.request) {
TraceUtils.error(context.request.method + ' ' +
((context.user && context.user.name) || 'unknown') + ' ' +
context.request.url);
}
//log error
TraceUtils.error(err);
//get response object
var response = context.response;
// if response is null exit
if (response == null) {
return callback();
}
// if response headers have been sent exit
if (response._headerSent) {
return callback();
}
if (context.format) {
/**
* try to find an error handler based on current request
* @type Function
*/
var errorHandler = this.errors[context.format];
if (typeof errorHandler === 'function') {
return errorHandler(context, err, function(err) {
if (err) {
TraceUtils.error('An error occurred while handling request error');
TraceUtils.error(err);
}
return callback();
});
}
}
onHtmlError(context, err, function(err) {
if (err) {
//send plain text
response.writeHead(err.statusCode || 500, {"Content-Type": "text/plain"});
//if error is an HTTP Exception
if (err instanceof HttpError) {
response.write(err.statusCode + ' ' + err.message + "\n");
}
else {
//otherwise send status 500
response.write('500 ' + err.message + "\n");
}
//send extra data (on development)
if (process.env.NODE_ENV === 'development') {
if (err.innerMessage) {
response.write(err.innerMessage + "\n");
}
if (err.stack) {
response.write(err.stack + "\n");
}
}
}
return callback();
});
}
catch (err) {
TraceUtils.log(err);
if (context.response) {
context.response.writeHead(500, {"Content-Type": "text/plain"});
context.response.write("500 Internal Server Error");
return callback.bind(this)();
}
}
}
/**
* @private
* @type {string}
*/
var HTTP_SERVER_DEFAULT_BIND = '127.0.0.1';
/**
* @private