This repository has been archived by the owner on Sep 16, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
1874 lines (1788 loc) · 61.9 KB
/
index.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
/**
* MOST Web Framework
* A JavaScript Web Framework
* http://themost.io
*
* Copyright (c) 2014, Kyriakos Barbounakis k.barbounakis@gmail.com, Anthi Oikonomou anthioikonomou@gmail.com
*
* Released under the BSD3-Clause license
* Date: 2014-06-10
*/
'use strict';
/**
* @private
*/
var common = require('./common'),
files = require('./files'),
_ = require('lodash'),
mvc = require('./http-mvc'),
html = require('./html'), util = require('util'), array = require('most-array'),
async = require('async'), path = require("path"), fs = require("fs"),
url = require('url'),
http = require('http'),
EventEmitter2 = require('most-data').types.EventEmitter2,
DataConfiguration = require('most-data').cfg.DataConfiguration,
querystring = require('querystring'),
HttpContext= require('./http-context').HttpContext,
DataException = require('most-data/types').DataException,
decorators = require('./decorators'),
crypto = require('crypto');
var Symbol = require('symbol');
var executionPathProperty = Symbol('executionPath');
var configPathProperty = Symbol('configPath');
var strategiesProperty = Symbol('strategies');
/**
* @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();
*/
function ApplicationOptions() {
}
/**
* Represents a configuration file that is applicable to an application or service.
* @constructor
*/
function ApplicationConfig() {
/**
* Gets an array of data adapters.
* @type {Array}
*/
this.adapters = [];
/**
* Gets an array of HTTP view engines configuration
* @type {Array}
*/
this.engines = [];
/**
* Gets an array of all registered MIME types
* @type {Array}
*/
this.mimes = [];
/**
* Gets an array of all registered HTTP handlers.
* @type {Array}
*/
this.handlers = [];
/**
* Gets an array of all registered HTTP routes.
* @type {Array}
*/
this.routes = [];
/**
* Gets or sets a collection of data adapter types that are going to be use in data operation
* @type {Array}
*/
this.adapterTypes = null;
/**
* Gets or sets a collection of data types that are going to be use in data operation
* @type {Array}
*/
this.dataTypes = null;
/**
* Gets or sets an object that holds application settings
* @type {Array}
*/
this.settings = { };
/**
* Gets or sets an object that holds application locales
* @type {*}
*/
this.locales = { };
}
/**
* Abstract class that represents a data context
* @constructor
*/
function HttpDataContext() {
//
}
/**
* @returns {AbstractAdapter}
*/
HttpDataContext.prototype.db = function () {
return null;
};
/**
* @param {string} name
* @returns {DataModel}
*/
HttpDataContext.prototype.model = function (name) {
return null;
};
/**
* @param {string} type
* @returns {*}
*/
HttpDataContext.prototype.dataTypes = function (type) {
return null;
};
/**
* @classdesc An abstract class that represents an HTTP Handler
* @class HttpHandler
* @abstract
* @constructor
*/
function HttpHandler() {
//
}
/**
* @type {string[]}
* @private
*/
HttpHandler.Events = ['beginRequest', 'validateRequest', 'authenticateRequest',
'authorizeRequest', 'mapRequest', 'postMapRequest', 'preExecuteResult', 'postExecuteResult', 'endRequest'];
/**
* Occurs as the first event in the HTTP execution
* @param {HttpContext} context
* @param {Function} callback
*/
HttpHandler.prototype.beginRequest = function (context, callback) {
callback = callback || function () {
};
callback.call(context);
};
/**
* Occurs when a handler is going to validate current HTTP request.
* @param {HttpContext} context
* @param {Function} callback
*/
HttpHandler.prototype.validateRequest = function (context, callback) {
callback = callback || function () {
};
callback.call(context);
};
/**
* Occurs when a handler is going to set current user identity.
* @param {HttpContext} context
* @param {Function} callback
*/
HttpHandler.prototype.authenticateRequest = function (context, callback) {
callback = callback || function () {
};
callback.call(context);
};
/**
* Occurs when a handler has established the identity of the current user.
* @param {HttpContext} context
* @param {Function} callback
*/
/*HttpHandler.prototype.postAuthenticateRequest = function(context, callback) {
callback = callback || function() {};
callback.call(context);
};*/
/**
* Occurs when a handler has verified user authorization.
* @param {HttpContext} context
* @param {Function} callback
*/
HttpHandler.prototype.authorizeRequest = function (context, callback) {
callback = callback || function () {
};
callback.call(context);
};
/**
* Occurs when the handler is selected to respond to the request.
* @param {HttpContext} context
* @param {Function} callback
*/
HttpHandler.prototype.mapRequest = function (context, callback) {
callback = callback || function () {
};
callback.call(context);
};
/**
* Occurs when application has mapped the current request to the appropriate handler.
* @param {HttpContext} context
* @param {Function} callback
*/
HttpHandler.prototype.postMapRequest = function(context, callback) {
callback = callback || function() {};
callback.call(context);
};
/**
* Occurs just before application starts executing a handler.
* @param {HttpContext} context
* @param {Function} callback
*/
/*HttpHandler.prototype.preRequestHandlerExecute = function(context, callback) {
callback = callback || function() {};
callback.call(context);
};*/
/**
* Occurs when application starts processing current HTTP request.
* @param {HttpContext} context
* @param {Function} callback
*/
HttpHandler.prototype.processRequest = function (context, callback) {
callback = callback || function () {
};
callback.call(context);
};
/**
* Occurs when application starts executing an HTTP Result.
* @param {HttpContext} context
* @param {Function} callback
*/
HttpHandler.prototype.preExecuteResult = function (context, callback) {
callback = callback || function () {
};
callback.call(context);
};
/**
* Occurs when application was succesfully executes an HTTP Result.
* @param {HttpContext} context
* @param {Function} callback
*/
HttpHandler.prototype.postExecuteResult = function (context, callback) {
callback = callback || function () {
};
callback.call(context);
};
/**
* Occurs when the handler finishes execution.
* @param {HttpContext} context
* @param {Function} callback
*/
/*HttpHandler.prototype.postRequestHandlerExecute = function(context, callback) {
callback = callback || function() {};
callback.call(context);
};*/
/**
* Occurs as the last event in the HTTP execution
* @param {HttpContext} context
* @param {Function} callback
*/
HttpHandler.prototype.endRequest = function (context, callback) {
callback = callback || function () {
};
callback.call(context);
};
/**
* @class HttpApplication
* @constructor
* @param {string} executionPath
* @augments EventEmitter
*/
function HttpApplication(executionPath) {
/**
* sets the current execution path
*/
this[executionPathProperty] = _.isNil(executionPath) ? path.join(process.cwd(), 'app') : path.join(executionPath, 'app');
/**
* Gets the current application configuration path
* @type {*}
*/
this[configPathProperty] = _.isNil(executionPath) ? path.join(process.cwd(), 'config') : path.join(executionPath, 'config');
/**
* Gets or sets application configuration settings
* @type {ApplicationConfig}
*/
this.config = null;
/**
* Gets or sets a collection of application handlers
* @type {Array}
*/
this.handlers = [];
//initialize angular server module
var ng = require('./angular-server-module');
/**
* @type {AngularServerModule}
*/
this.module = null;
//init module
ng.init(this);
//register auth service
var self = this;
self.module.service('$auth', function($context) {
//ensure settings
self.config.settings.auth = self.config.settings.auth || { };
var providerPath = self.config.settings.auth.provider || './auth-service';
//get auth provider
if (providerPath.indexOf('/')===0)
providerPath = self.mapPath(providerPath);
var svc = require(providerPath);
if (typeof svc.createInstance !== 'function')
throw new Error('Invalid authentication provider module.');
return svc.createInstance($context);
});
/**
* @type {HttpCache}
*/
var $cache;
self.module.service('$cache', function() {
try {
return self.cache;
}
catch (e) {
throw e;
}
});
Object.defineProperty(self, 'cache', {
get: function () {
if (!web.common.isNullOrUndefined($cache))
return $cache;
var HttpCache = require( "./http-cache" );
/**
* @type {HttpCache|*}
*/
$cache = new HttpCache();
return $cache;
},
set: function(value) {
$cache = value;
},
configurable: false,
enumerable: false
});
/**
* Gets or sets a boolean that indicates whether the application is in development mode
* @type {string}
*/
this.development = (process.env.NODE_ENV === 'development');
/**
*
* @type {{html, text, json, unauthorized}|*}
*/
this.errors = httpApplicationErrors(this);
}
util.inherits(HttpApplication, EventEmitter2);
HttpApplication.prototype.getExecutionPath = function() {
return this[executionPathProperty];
};
HttpApplication.prototype.getConfigurationPath = function() {
return this[configPathProperty];
};
/**
* Initializes application configuration.
* @return {HttpApplication}
*/
HttpApplication.prototype.init = function () {
/**
* Gets or sets application configuration settings
*/
//get node environment
var env = process.env['NODE_ENV'] || 'production', str;
//first of all try to load environment specific configuration
try {
common.log(util.format('Init: Loading environment specific configuration file (app.%s.json)', env));
str = path.join(this.getConfigurationPath(), 'app.' + env + '.json');
/**
* @type {ApplicationConfig}
*/
this.config = require(str);
common.log(util.format('Init: Environment specific configuration file (app.%s.json) was succesfully loaded.', env));
}
catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
common.log(util.format('Init: Environment specific configuration file (app.%s.json) is missing.', env));
//try to load default configuration file
try {
common.log('Init: Loading environment default configuration file (app.json)');
str = path.join(this.getConfigurationPath(), 'app.json');
/**
* @type {ApplicationConfig}
*/
this.config = require(str);
common.log('Init: Default configuration file (app.json) was succesfully loaded.');
}
catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
common.log('Init: An error occured while loading default configuration (app.json). Configuration cannot be found or is inaccesible.');
//load internal configuration file
/**
* @type {ApplicationConfig}
*/
this.config = require('./app.json');
this.config.settings.crypto = {
"algorithm": "aes256",
"key": common.randomHex(32)
};
common.log('Init: Internal configuration file (app.json) was succesfully loaded.');
}
else {
common.log('Init: An error occured while loading default configuration (app.json)');
throw e;
}
}
}
else {
common.log(util.format('Init: An error occured while loading application specific configuration (app).', env));
throw e;
}
}
//load routes (if empty)
if (web.common.isNullOrUndefined(this.config.routes)) {
try {
this.config.routes = require(path.resolve(this.getConfigurationPath(),'routes.json'));
}
catch(e) {
if (e.code === 'MODULE_NOT_FOUND') {
//load internal default route file
web.common.log('Init: Application specific routes configuration cannot be found. The default routes configuration will be loaded instead.');
this.config.routes = require('./routes.json');
}
else {
web.common.log('Init: An error occured while trying to load application routes configuration.');
throw e;
}
}
}
//load data types (if empty)
if (web.common.isNullOrUndefined(this.config.dataTypes))
{
try {
var dataConfiguration = new DataConfiguration(this[configPathProperty]);
this.config.dataTypes = dataConfiguration.dataTypes;
}
catch(e) {
web.common.log('Init: An error occured while trying to load application data types configuration.');
throw e;
}
}
//set settings default
this.config.settings = this.config.settings || {};
//initialize handlers list
//important note: Applications handlers are static classes (they will be initialized once),
//so they should not hold information about http context and execution lifecycle.
var self = this;
var handlers = self.config.handlers || [], defaultApplicationConfig = require('./app.json');
//default handlers
var defaultHandlers = defaultApplicationConfig.handlers;
for (var i = 0; i < defaultHandlers.length; i++) {
(function(item) {
if (typeof handlers.filter(function(x) { return x.name === item.name; })[0] === 'undefined') {
handlers.push(item);
}
})(defaultHandlers[i]);
}
array(handlers).each(function (h) {
try {
var handlerPath = h.type;
if (handlerPath.indexOf('/')==0)
handlerPath = self.mapPath(handlerPath);
var handlerModule = require(handlerPath), handler = null;
if (handlerModule) {
if (typeof handlerModule.createInstance != 'function') {
console.log(util.format('The specified handler (%s) cannot be instantiated. The module does not export createInstance() function.', h.name));
return;
}
handler = handlerModule.createInstance();
if (handler)
self.handlers.push(handler);
}
}
catch (e) {
throw new Error(util.format('The specified handler (%s) cannot be loaded. %s', h.name, e.message));
}
});
//initialize basic directives collection
var directives = require("./angular-server-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);
};
/**
* Resolves ETag header for the given file. If the specifed 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);
}
});
};
/**
* @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 (e) {
console.log(e);
callback(null, false);
}
};
/**
* @param request {String|IncomingMessage}
* */
HttpApplication.prototype.resolveMime = function (request) {
if (typeof request=== 'string') {
//get file extension
var extensionName = path.extname(request);
var arr = this.config.mimes.filter(function(x) {
return (x.extension == extensionName);
});
if (arr.length>0)
return arr[0];
return null;
}
else if (typeof request=== 'object') {
//get file extension
var extensionName = path.extname(request.url);
var arr = this.config.mimes.filter(function(x) {
return (x.extension == extensionName);
});
if (arr.length>0)
return arr[0];
return null;
}
};
/**
* Encrypts the given data
* */
HttpApplication.prototype.encrypt = function (data)
{
if (typeof data === 'undefined' || data===null)
return null;
//validate settings
if (!this.config.settings.crypto)
throw new Error('Data encryption configuration section is missing. The operation cannot be completed');
if (!this.config.settings.crypto.algorithm)
throw new Error('Data encryption algorithm is missing. The operation cannot be completed');
if (!this.config.settings.crypto.key)
throw new Error('Data encryption key is missing. The operation cannot be completed');
//encrypt
var cipher = crypto.createCipher(this.config.settings.crypto.algorithm, this.config.settings.crypto.key);
return cipher.update(data, 'utf8', 'hex') + cipher.final('hex');
};
/**
* Decrypts the given data.
* */
HttpApplication.prototype.decrypt = function (data)
{
if (typeof data === 'undefined' || data==null)
return null;
//validate settings
if (!this.config.settings.crypto)
throw new Error('Data encryption configuration section is missing. The operation cannot be completed');
if (!this.config.settings.crypto.algorithm)
throw new Error('Data encryption algorithm is missing. The operation cannot be completed');
if (!this.config.settings.crypto.key)
throw new Error('Data encryption key is missing. The operation cannot be completed');
//decrypt
var decipher = crypto.createDecipher(this.config.settings.crypto.algorithm, this.config.settings.crypto.key);
return decipher.update(data, 'hex', 'utf8') + decipher.final('utf8');
};
/**
* Sets the authentication cookie that is associated with the given user.
* @param {HttpContext} context
* @param {String} username
* @param {*=} options
*/
HttpApplication.prototype.setAuthCookie = function (context, username, options)
{
var defaultOptions = { user:username, dateCreated:new Date()}, value, expires;
if (typeof options !== 'undefined' && options != null) {
value = JSON.stringify(util._extend(options, defaultOptions));
if (util.isDate(options.expires)) {
expires = options.expires.toUTCString();
}
}
else {
value = JSON.stringify(defaultOptions);
}
var settings = this.config.settings ? (this.config.settings.auth || { }) : { } ;
settings.name = settings.name || '.MAUTH';
var str = settings.name.concat('=', this.encrypt(value)) + ';path=/';
if (typeof expires === 'string') {
str +=';expires=' + expires;
}
context.response.setHeader('Set-Cookie',str);
};
/**
* Sets the authentication cookie that is associated with the given user.
* @param {HttpContext} context
* @param {String} username
*/
HttpApplication.prototype.getAuthCookie = function (context)
{
try {
var settings = this.config.settings ? (this.config.settings.auth || { }) : { } ;
settings.name = settings.name || '.MAUTH';
var cookie = context.cookie(settings.name);
if (cookie) {
return this.decrypt(cookie);
}
return null;
}
catch(e) {
console.log('GetAuthCookie failed.');
console.log(e.message);
return null;
}
};
/**
*
* @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 common.HttpNotFoundException();
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 {AbstractAdapter}
*/
HttpApplication.prototype.db = function () {
if ((this.config.adapters === null) || (this.config.adapters.length === 0))
throw new Error('Data adapters configuration settings are missing or cannot be accessed.');
var adapter = null;
if (this.config.adapters.length === 1) {
//there is only one adapter so try to instantiate it
adapter = this.config.adapters[0];
}
else {
adapter = array(this.config.adapters).firstOrDefault(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 = this.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().')
}
};
HttpApplication.prototype.setContextProvider = function(provider) {
if (typeof provider === 'undefined' || provider === null) {
throw new TypeError('Context provider may not be null.');
}
if (typeof provider.createInstance !== 'function') {
throw new TypeError('Context provider does not implement createInstance() method.');
}
this.module.service('contextProvider', function() {
return provider;
});
};
HttpApplication.prototype.getContextProvider = function() {
var contextProviderSvc = this.module.service('contextProvider');
if (typeof contextProviderSvc !== 'function') {
var httpContext = require('./http-context');
this.module.service('contextProvider', function() {
return httpContext;
});
return httpContext;
}
return contextProviderSvc();
};
/**
* Creates an instance of HttpContext class.
* @param {ClientRequest} request
* @param {ServerResponse} response
* @returns {HttpContext}
*/
HttpApplication.prototype.createContext = function (request, response) {
var context = this.getContextProvider().createInstance(request, response);
//set context application
context.application = this;
//set handler events
for (var i = 0; i < HttpHandler.Events.length; i++) {
var ev = HttpHandler.Events[i];
for (var j = 0; j < this.handlers.length; j++) {
var handler = this.handlers[j];
if (typeof handler[ev] === 'function') {
context.on(ev, handler[ev]);
}
}
}
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
/**
* @type {{unattendedExecutionAccount:string}|*}
*/
this.config.settings.auth = this.config.settings.auth || {};
var account = this.config.settings.auth.unattendedExecutionAccount;
//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(util.format('/extensions/%s.js', extension));
if (fs.existsSync(extensionPath)) {
//load extension
require(extensionPath);
}
}
}
return this;
};
/**
*
* @param {*|string} options
* @param {Function} callback
*/