-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathindex.js
More file actions
1519 lines (1297 loc) · 54.2 KB
/
index.js
File metadata and controls
1519 lines (1297 loc) · 54.2 KB
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
/**
* Twee Framework Functionality
*/
"use strict";
var express = require('express')
, debug = require('debug')('twee.io')
, path = require('path')
, colors = require('colors/safe')
, fs = require('fs')
, extend = require('./utils/extend')
, events = require('events');
/**
* twee Framework Class
* @constructor
*/
function twee() {
/**
* Express Application Instance
* @type express()
* @private
*/
this.__app = express();
/**
* Flag that shows that framework already bootstrapped
* @type {boolean}
* @private
*/
this.__bootstraped = false;
/**
* Base Directory for including all the modules
* @type {string}
* @private
*/
this.__baseDirectory = '';
/**
* Environment
* @type {string}
* @private
*/
this.__env = 'production';
/**
* Configuration object. Stores all the modules configs and core config
* @type {{}}
* @private
*/
this.__config = {};
/**
* Default Module Options
* @type {{disabled: boolean, prefix: string, disableViewEngine: boolean}}
* @private
*/
this.__defaultModuleOptions = {
disabled: false,
prefix: '/'
};
/**
* Registry of extensions to avoid infinity recursion
* @type {{}}
* @private
*/
this.__extensionsRegistry = {};
/**
* View helpers registry
* @type {}
*/
this.helper = {};
/**
* It allows us to call in views:
* {{ helper.foo(..) }} or {{ helper['foo'](...) }}
* BUT! NOT: {{ foo(...) }} because it can be overwritten by usual passed variables.
* So we should protect each of them. We don't want to care about this. So we'll protect only `helper` name.
* @type {*}
*/
this.__app.locals.helper = this.helper;
/**
* Extending one config from another
* @type {*|exports}
*/
this.extend = extend;
/**
* HTTP Server instance
* @type {null}
* @private
*/
this.__http = null;
/**
* HTTPS Server instance
* @type {null}
* @private
*/
this.__https = null;
/**
* For recursy control
* @type {number}
* @private
*/
this.__extensionsRecursyDeepness = 0;
/**
* Registry of different objects
* @type {{}}
* @private
*/
this.__registry = {};
/**
* Registry of middleware lists that are used in dispatch process of Express
* @type {{}}
* @private
*/
this.__middlewareListRegistry = {};
}
/**
* Setting prototype of framework
*/
twee.prototype.__proto__ = new events.EventEmitter();
/**
* Getting Application Instance
*/
twee.prototype.getApplication = function() {
return this.__app;
};
/**
* Logging message to console
* @param message
* @returns {twee}
*/
twee.prototype.log = function(message) {
debug(colors.cyan('[WORKER:' + process.pid + '] ') + colors.yellow(message));
return this;
};
/**
* Logging error to console
* @param message
* @returns {twee}
*/
twee.prototype.error = function(message) {
debug(colors.cyan('[WORKER:' + process.pid + '][ERROR] ') + colors.red(message.stack || message.toString()));
return this;
};
/**
* Bootstrapping application
* @param options Object
* @returns {twee}
*/
twee.prototype.Bootstrap = function(options) {
if (this.__bootstraped) {
return this;
}
var self = this;
options = options || {};
// This is default config state. It can be overwritten before running
options = extend(true, {
modules: 'configs/modules',
tweeConfig: 'configs/twee'
}, options);
process.on('uncaughtException', function(err) {
self.error('Caught exception: ' + err.stack || err.toString());
//console.trace();
self.emit('twee.Exception', err, self);
});
process.on('SIGINT', function(){
// Generate event for all the modules to free some resources
self.emit('twee.Exit');
self.log('Exiting');
self.__http && self.__http.close();
self.__https && self.__http.close();
process.exit(0);
});
try {
this.__bootstrap(options);
} catch (err) {
throw new Error('Bootstrap Error: ' + err.stack || err.toString());
}
this.__bootstraped = true;
return this;
};
/**
* Common bootstrap process is wrapped with exception catcher
* @param options
* @returns {twee}
* @private
*/
twee.prototype.__bootstrap = function(options) {
var self = this;
this.emit('twee.Bootstrap.Start');
if (!options || !options.modules) {
throw new Error('Modules field should not be empty!');
}
var modules = options.modules;
// If this is file path with modules configuration - then load it
if (typeof modules == 'string') {
modules = this.Require(modules);
this.emit('twee.Bootstrap.ModulesList', modules);
}
if (typeof modules != 'object') {
throw new Error('Modules should be file path or Object');
}
// Loading default framework configuration
var tweeConfig = require('./configs/default');
this.emit('twee.Bootstrap.DefaultConfig', tweeConfig);
// Extending framework configuration during Bootstrapping
if (options.tweeConfig) {
if (typeof options.tweeConfig == 'string') {
var tweeConfigFullPath = path.join(this.__baseDirectory, options.tweeConfig);
try {
var loadedTweeConfig = require(tweeConfigFullPath);
tweeConfig = extend(true, tweeConfig, loadedTweeConfig);
this.emit('twee.Bootstrap.ExtendedConfig', tweeConfig);
} catch (e) {
this.log('[WARNING] No valid twee main config specified! Using default values.');
}
// Extending config with environment-specified configuration
var directory = path.dirname(tweeConfigFullPath)
, configFile = path.basename(tweeConfigFullPath)
, environmentConfig = directory + '/' + this.__env + '/' + configFile;
try {
var envTweeConfig = require(environmentConfig);
tweeConfig = extend(true, tweeConfig, envTweeConfig);
this.emit('twee.Bootstrap.ExtendedEnvConfig', tweeConfig);
} catch (err) {
// Nothing to do here. Just no config for environment
}
}
}
// Setting up framework config
this.__config.twee = tweeConfig;
this.emit('twee.Bootstrap.Config', tweeConfig);
// Setting package information
this.__config.twee.package = this.Require('package');
this.emit('twee.Bootstrap.PackageInfo');
// Extension specific configs
this.__config.twee.extension = this.__config.twee.extension || {};
// Setting framework object as global
global.twee = this;
// Pre-loading all the modules configs, routes, patterns and other stuff
this.LoadModulesInformation(modules);
this.emit('twee.Bootstrap.ModulesInformationLoaded');
// Load enabled twee core extensions
this.emit('twee.Bootstrap.TweeExtensionsPreLoad');
this.LoadExtensions(this.getConfig('twee:extensions', {}), null);
this.emit('twee.Bootstrap.TweeExtensionsLoaded');
// All the extensions that execute random not-standard or standard code - runs before everything
this.LoadModulesExtensions();
this.emit('twee.Bootstrap.ModulesExtensionsLoaded');
// Lifting the server because some extensions could require http-server object
// before all the routes has been setup. for example socket.io
this.__createServer();
// Head middlewares are module-specific and used to initialize something into req or res objects
this.LoadModulesMiddleware('head');
this.emit('twee.Bootstrap.ModulesHeadMiddlewareLoaded');
// Controllers is the place where all the business logic is concentrated
this.LoadModulesControllers();
this.emit('twee.Bootstrap.ModulesControllersLoaded');
// Tail middleware is used for logging and doing post-calculations, post-stuff
this.LoadModulesMiddleware('tail');
this.emit('twee.Bootstrap.ModulesTailMiddlewareLoaded');
// This route will be used to write user that he did not sat up any configuration file for framework
this.__handle404();
this.emit('twee.Bootstrap.End');
return this;
};
/**
* Loading turned on twee extensions
*
* @param extensions Object - Extensions object where keys are the names of extensions
* @param moduleName String The name of current module
* @returns {twee}
*/
twee.prototype.LoadExtensions = function(extensions, moduleName) {
for (var extension_name in extensions) {
extensions[extension_name].name = extension_name;
this.__resolveDependencies(extensions[extension_name], extensions, moduleName);
}
return this;
};
/**
* Generating extension unique ID for registry
* @param extension
* @param moduleName
* @returns {string}
* @private
*/
twee.prototype.__getExtensionUniqueID = function(extension, moduleName) {
return 'module:' + (moduleName || 'twee')
+ (extension.file ? '|file:' + extension.file : '')
+ (extension.module ? '|npm-module:' + extension.module : '')
+ (extension.applicationModule ? '|appModule:' + extension.applicationModule : '');
};
/**
* Loading all the extensions and it's dependencies tree
*
* @param currentExtension
* @param extensions
* @param moduleName
* @private
*/
twee.prototype.__resolveDependencies = function(currentExtension, extensions, moduleName) {
this.emit('twee.LoadExtensions.PreLoad', currentExtension, moduleName);
var extensionID = this.__getExtensionUniqueID(currentExtension, moduleName);
if (this.__extensionsRegistry[extensionID]) {
return;
}
this.__extensionsRegistry[extensionID] = {options: currentExtension, extension: null};
var moduleLog = moduleName ? '[MODULE::' + moduleName + ']' : '';
// Dependencies are loaded only when needed by another extensions
if (currentExtension.dependency || (currentExtension.disabled && !currentExtension.dependency)) {
return;
}
var currentExtensionDependencies;
currentExtensionDependencies = {};
// First of all trying to import extension and load it's internal dependencies definition
if (!currentExtension.module && !currentExtension.file) {
moduleLog += ('[EXTENSION' + (moduleLog ? '' : '::GLOBAL') + '] ');
throw new Error(moduleLog + colors.cyan(currentExtension.name) + '` has wrong configuration. `module` AND `file` are not correct');
}
// Loading extension module
var extensionModule = ''
, extensionModuleFolder = '';
try {
// This is simply local file or module
if (currentExtension.file) {
if (currentExtension.applicationModule) {
try {
extensionModuleFolder = this.__config['__folders__'][currentExtension.applicationModule]['moduleExtensionsFolder'];
extensionModule = require(extensionModuleFolder + currentExtension.file);
} catch (err) {
//noinspection ExceptionCaughtLocallyJS
throw new Error('Module `' + currentExtension.applicationModule
+ '` is not installed. Needed as dependency provider for extension: '
+ currentExtension.name + '. ' + err.stack || err.toString());
}
} else if (moduleName) {
extensionModuleFolder = this.__config['__folders__'][moduleName]['moduleExtensionsFolder'];
extensionModule = require(extensionModuleFolder + currentExtension.file);
} else {
//noinspection ExceptionCaughtLocallyJS
throw new Error('Extension is wrong configured: ' + JSON.stringify(currentExtension));
}
// This is npm module
} else if (currentExtension.module) {
extensionModule = require(currentExtension.module);
}
} catch (err) {
throw err;
}
if (!extensionModule.extension || typeof extensionModule.extension !== 'function') {
moduleLog += ('[EXTENSION' + (moduleLog ? '' : '::GLOBAL') + '] ');
throw new Error(moduleLog + extensionID + ' should export .extension as `function`');
}
this.__extensionsRegistry[extensionID].extension = extensionModule.extension;
currentExtensionDependencies = extensionModule.dependencies || {};
if (currentExtension.dependencies && typeof currentExtension.dependencies == 'object' && Object.keys(currentExtension.dependencies).length) {
// Overwrite dependencies configuration if local configuration presents. It has greater priority
currentExtensionDependencies = currentExtension.dependencies;
}
for (var dep in currentExtensionDependencies) {
var dependency = currentExtensionDependencies[dep];
if (dependency.disabled) {
continue;
}
try {
if (!dependency || typeof dependency !== 'object' || !Object.keys(dependency).length) {
// It means that dependency is empty object or we have only it's name
// And should search in global extensions namespace
if (!extensions[dep]) {
//noinspection ExceptionCaughtLocallyJS
throw new Error('Dependency info does not exists neither in dependency config nor in global extensions namespace');
}
dependency = extensions[dep];
dependency.dependency = false;
}
dependency.name = dep;
this.__extensionsRecursyDeepness++;
if (this.__extensionsRecursyDeepness > 100) {
throw new Error('It seems we have dependencies recursy infinity loop');
}
this.__resolveDependencies(dependency, extensions, moduleName);
this.__extensionsRecursyDeepness--;
} catch (err) {
throw new Error('Current Extension: `' + currentExtension.name + '`, dependency: `' + dep + '` exception: ' + err.stack || err.toString());
}
}
moduleLog += ('[EXTENSION::' + currentExtension.name + '] ');
if (extensionModule.config && typeof extensionModule.config === 'object') {
var configNamespace = extensionModule.configNamespace || '';
if (configNamespace) {
// Rewrite extension's config with application
this.__config['twee']['extension'][configNamespace] = this.__config['twee']['extension'][configNamespace] || {};
this.__config['twee']['extension'][configNamespace] = this.extend(true, extensionModule.config, this.__config['twee']['extension'][configNamespace]);
}
}
extensionModule.extension();
this.log(moduleLog + 'Installed (configNamespace: ' + configNamespace + ')');
this.emit('twee.LoadExtensions.Loaded', currentExtension, moduleName);
};
/**
* Loading all the modules
*
* @returns {twee}
*/
twee.prototype.LoadModulesControllers = function() {
for (var moduleName in this.__config['__moduleOptions__']) {
this.setupRoutes(moduleName, this.__config['__moduleOptions__'][moduleName].prefix || '');
}
return this;
};
/**
* Loading all the middlewares from all modules that should be dispatched before any constructor
* Head middlewares are executed before all the controllers. It is like preDispatch.
* Tail middlewares are executed after all the controllers. It is like postDispatch.
*
* @param placement String Placement of middleware: head or tail.
* @returns {twee}
*/
twee.prototype.LoadModulesMiddleware = function(placement) {
placement = String(placement || '').trim();
if (placement !== 'head' && placement !== 'tail') {
throw new Error('Middleware type should be `head` or `tail`');
}
this.emit('twee.LoadModulesMiddleware.Start', placement);
for (var moduleName in this.__config['__moduleOptions__']) {
this.emit('twee.LoadModulesMiddleware.OnLoad', placement, moduleName);
var middlewareList = this.getConfig('__setup__:' + moduleName + ':middleware:' + placement) || []
, middlewareInstanceList = this.getMiddlewareInstanceArray(moduleName, middlewareList);
if (middlewareInstanceList.length) {
var prefix = String(this.__config['__moduleOptions__'][moduleName].prefix || '').trim();
if (prefix) {
this.__app.use(prefix, middlewareInstanceList);
} else {
this.__app.use(middlewareInstanceList);
}
}
this.emit('twee.LoadModulesMiddleware.Loaded', placement, moduleName);
}
this.emit('twee.LoadModulesMiddleware.End', placement);
return this;
};
/**
* Loading all extensions from all the modules by order:
* ModulesOrder -> ExtensionsOrderInEveryModule
*
* @returns {twee}
*/
twee.prototype.LoadModulesExtensions = function() {
this.emit('twee.LoadModulesExtensions.Start');
for (var moduleName in this.__config['__moduleOptions__']) {
if (this.__config['__setup__'][moduleName]['extensions']) {
if (typeof this.__config['__setup__'][moduleName]['extensions'] != 'object') {
continue;
}
var extensions = this.__config['__setup__'][moduleName]['extensions'];
this.emit('twee.LoadModulesExtensions.LoadExtensions.Start', moduleName, extensions);
this.LoadExtensions(extensions, moduleName);
this.emit('twee.LoadModulesExtensions.LoadExtensions.Stop', moduleName, extensions);
}
}
this.emit('twee.LoadModulesExtensions.Stop');
return this;
};
/**
* Default 404 route
* @private
*/
twee.prototype.__handle404 = function() {
var self = this;
// Here we can rewrite environment with framework extending
this.emit('twee.__handle404.Start');
function generate404(req, res, next) {
next(new Error('Not Found!'));
}
function errorHandler(err, req, res, next) {
var message = '404 - Not found!';
if (err) {
res.status(500);
if (self.__env == 'development') {
message = err.toString();
}
} else {
res.status(404);
err = new Error('The page you requested has not been found!');
}
if (req.xhr) {
var jsonMessage = {message: message, error_code: 404};
if (self.__env == 'development') {
jsonMessage['stack'] = err.stack || err.toString();
}
res.json(jsonMessage);
} else {
if (self.__app.get('view engine')) {
res.render(path.resolve(self.getConfig('twee:options:errorPages:404:viewTemplate')), {error: err});
} else {
res.send('<h1>' + message + '</h1>');
}
}
}
this.__app.use(generate404, errorHandler);
this.emit('twee.__handle404.End');
};
/**
* Loading modules information
*
* @param modules
* @return {twee}
*/
twee.prototype.LoadModulesInformation = function(modules) {
this.emit('twee.LoadModulesInformation.Start');
for (var moduleName in modules) {
var moduleOptions = modules[moduleName];
if (moduleOptions.disabled == true) {
this.log('Module `' + moduleName + '` disabled. Skipping.');
continue;
}
this.__config['__moduleOptions__'] = this.__config['__moduleOptions__'] || {};
this.__config['__moduleOptions__'][moduleName] = moduleOptions;
this.LoadModuleInformation(moduleName, moduleOptions);
}
this.emit('twee.LoadModulesInformation.End');
return this;
};
/**
* Loading one module, including all the configs, middlewares and controllers
* @param moduleName
* @param moduleOptions
* @returns {twee}
* @constructor
*/
twee.prototype.LoadModuleInformation = function(moduleName, moduleOptions) {
this.emit('twee.LoadModuleInformation.Start', moduleName, moduleOptions);
this.log('[MODULE] Loading: ' + colors.cyan(moduleName));
moduleName = String(moduleName || '').trim();
if (!moduleName) {
throw new Error('twee::LoadModuleInformation - `moduleName` is empty');
}
if (moduleName == 'twee') {
throw new Error('twee::LoadModuleInformation - `twee` name for modules is deprecated. It is used for framework');
}
var moduleFolder = path.join(this.__baseDirectory, 'modules', moduleName + '/')
, moduleSetupFolder = path.join(moduleFolder, 'setup/')
, moduleSetupFile = path.join(moduleFolder, 'setup/setup')
, moduleConfigsFolder = path.join(moduleFolder, 'setup/configs/')
, moduleControllersFolder = path.join(moduleFolder, 'controllers/')
, moduleModelsFolder = path.join(moduleFolder, 'models/')
, moduleMiddlewareFolder = path.join(moduleFolder, 'middleware/')
, moduleParamsFolder = path.join(moduleFolder, 'params/')
, moduleViewsFolder = path.join(moduleFolder, 'views/')
, moduleExtensionsFolder = path.join(moduleFolder, 'extensions/')
, moduleI18nFolder = path.join(moduleFolder, 'i18n/')
, moduleAssetsFolder = path.join(moduleFolder, 'assets/');
this.__config['__folders__'] = this.__config['__folders__'] || {};
this.__config['__folders__'][moduleName] = {
module: moduleFolder,
moduleSetupFolder: moduleSetupFolder,
moduleSetupFile: moduleSetupFile,
moduleConfigsFolder: moduleConfigsFolder,
moduleControllersFolder: moduleControllersFolder,
moduleModelsFolder: moduleModelsFolder,
moduleMiddlewareFolder: moduleMiddlewareFolder,
moduleParamsFolder: moduleParamsFolder,
moduleViewsFolder: moduleViewsFolder,
moduleExtensionsFolder: moduleExtensionsFolder,
moduleI18nFolder: moduleI18nFolder,
moduleAssetsFolder: moduleAssetsFolder
};
// Load base configs and overwrite them according to environment
this.loadConfigs(moduleName, moduleConfigsFolder);
// Loading Routes Information
this.__config['__setup__'] = this.__config['__setup__'] || {};
this.__config['__setup__'][moduleName] = require(moduleSetupFile);
this.emit(
'twee.LoadModuleInformation.End',
moduleName,
this.__config['__setup__'][moduleName],
this.__config['__folders__'][moduleName]
);
return this;
};
/**
* Loading all the bunch of configs from configuration folder according to environment
*
* @param configsFolder string - configurations folder
* @returns {twee}
* @param moduleName
*/
twee.prototype.loadConfigs = function(moduleName, configsFolder) {
this.emit('twee.loadConfigs.Start', moduleName, configsFolder);
var self = this
, configs = fs.readdirSync(configsFolder)
, configsObject = {};
configs.forEach(function(configFile){
var configFilePath = path.join(configsFolder, configFile)
, stats = fs.statSync(configFilePath);
if (stats.isFile()) {
var configData = self.loadConfig(configFilePath, moduleName);
var cD = {};
cD[configData["name"]] = configData.config;
configsObject = extend(true, configsObject, cD);
}
});
configsFolder = path.join(configsFolder, this.__env);
if (fs.existsSync(configsFolder)) {
configs = fs.readdirSync(configsFolder);
configs.forEach(function(configFile){
var configFilePath = path.join(configsFolder, configFile)
, stats = fs.statSync(configFilePath);
if (stats.isFile()) {
var configData = self.loadConfig(configFilePath, moduleName);
var cD = {};
cD[configData["name"]] = configData.config;
configsObject = extend(true, configsObject, cD);
}
});
} else {
this.log('[WARNING] No environment configs exists');
}
this.__config[moduleName.toLowerCase()] = configsObject;
this.emit('twee.loadConfigs.End', moduleName, this.__config[moduleName]);
return this;
};
/**
* Loading config file and returning it's name and contents
* @param configFile
* @param moduleName
* @returns {{name: string, config: *}}
*/
twee.prototype.loadConfig = function(configFile, moduleName) {
this.emit('twee.loadConfig.Start', configFile, moduleName);
var configName = path.basename(configFile).toLowerCase().replace('.json', '').replace('.js', '')
, config = require(configFile);
this.log('[MODULE::' + moduleName + '][CONFIGS::' + configName + '] Loaded: ' + configFile);
config = {name: configName, config: config};
this.emit('twee.loadConfig.Start', configFile, moduleName, config);
return config;
};
/**
* Setting base directory for including all the rest
* @param directory
* @returns {twee}
*/
twee.prototype.setBaseDirectory = function(directory) {
directory = String(directory || '');
this.__baseDirectory = this.__baseDirectory || directory || process.cwd();
// Fixing environment
this.__env = process.env.NODE_ENV;
if (!this.__env) {
this.log('No NODE_ENV sat up. Setting to `production`');
this.__env = process.env.NODE_ENV = 'production';
}
this.log('NODE_ENV: ' + this.__env);
this.__app.locals.env = this.__env;
return this;
};
/**
* Returning root application directory or full subfolder
*
* @param postfix String Postfix to add to base directory
* @returns {string}
*/
twee.prototype.getBaseDirectory = function(postfix) {
if (typeof postfix === 'string') {
postfix = String(postfix || '').trim();
return path.join(this.__baseDirectory, postfix);
}
return this.__baseDirectory;
};
/**
* Including local module
* @param module
* @returns {*}
*/
twee.prototype.Require = function(module) {
return require(path.join(this.__baseDirectory, module));
};
/**
* Setting up params for routes
* @param params
* @param router
* @param moduleName
*/
twee.prototype.setupParams = function(params, router, moduleName) {
if (!router.param) {
throw new Error('Router should be instance of express.Router()');
}
if (params && params instanceof Object) {
for (var param in params) {
// Regexp can be used too
//console.log(param, typeof params[param]);
if (params[param] instanceof RegExp) {
var paramContents = params[param];
router.param(param, function(req, res, next, p){
if (p.match(paramContents)) {
next();
} else {
next('route');
}
});
this.log('[MODULE::' + moduleName + '][PARAM::' + param + '] Installed as RegExp(' + params[param] + ')');
// If it is middleware function from setup.js file - it could be passed as is too
} else if (typeof params[param] === 'function') {
var paramContents = params[param];
router.param(param, paramContents);
this.log('[MODULE::' + moduleName + '][PARAM::' + param + '] Installed as inline middleware');
// Otherwise it should be an instance or middleware function from file or module or applicationModule/params folder
} else if (typeof params[param] === 'object') {
// This is module
var requireString = '';
if (params[param].module && typeof params[param].module === 'string') {
requireString = params[param].module;
} else if (params[param].applicationModule
&& typeof params[param].applicationModule === 'string'
&& this.__config['__folders__'][params[param].applicationModule]) {
if (params[param].file && typeof params[param].file === 'string') {
requireString = this.__config['__folders__'][params[param].applicationModule]['moduleParamsFolder'];
requireString += params[param].file;
}
} else if (params[param].file && typeof params[param].file === 'string') {
requireString = this.__config['__folders__'][moduleName]['moduleParamsFolder'] + params[param].file;
}
if (requireString) {
var _module = require(requireString);
// If method specified - try to go in needed deepness to get right object
if (params[param].method) {
var methodParts = params[param].method.split('.')
, neededMethod = _module[methodParts[0]]
, previousMethod = null;
for (var i = 1; i < methodParts.length; i++) {
if (typeof neededMethod === 'function') {
neededMethod = neededMethod();
}
previousMethod = neededMethod;
if (neededMethod[methodParts[i]]) {
neededMethod = neededMethod[methodParts[i]];
}
}
// If it is regexp - then just use it as is
if (neededMethod instanceof RegExp) {
router.param(param, function(req, res, next, p){
if (p.match(neededMethod)) {
next();
} else {
next('route');
}
});
this.log('[MODULE::' + moduleName + '][PARAM::' + param + '] Installed as RegExp(' + params[param] + ')');
continue;
}
if (typeof neededMethod !== 'function') {
throw new Error('Method for router.param() neither RegExp nor Middleware Function');
}
// If we need to bind function to parent reference - then do it
if (params[param].reference && previousMethod instanceof Object) {
neededMethod = neededMethod.bind(previousMethod);
}
router.param(param, neededMethod);
this.log('[MODULE::' + moduleName + '][PARAM::' + param + '] Installed as middleware');
// if we have no specified method - then in case when it is middleware or RegExp - setup it
} else if (typeof _module === 'function' || _module instanceof RegExp) {
router.param(param, _module);
this.log('[MODULE::' + moduleName + '][PARAM::' + param + '] Installed as middleware');
}
}
}
}
}
};
/**
* Format for controllers in configuration:
* <ControllerName>Controller:<MethodName>Action:<get[,post[,all[...]]]>
*
* By default HTTP method is set to `all`. It means that all the HTTP methods are acceptable
*
* Example of Config:
* {
* "routes": [
* {
* "description": "Entry point for application. Landing page",
* "pattern": "/",
* "controllers": ["IndexController:indexAction"]
* }
* }
*
* Bundles of middlewares can be sat as:
* ["IndexController:authAction", "IndexController:indexAction"]
*
* @param moduleName string Module Name
* @param prefix string Module request prefix
* @returns {twee}
*/
twee.prototype.setupRoutes = function(moduleName, prefix) {
var routesFile = this.__config['__folders__'][moduleName]['moduleSetupFile']
, routes = require(routesFile)
// TODO: use options: http://expressjs.com/api.html#router
, router = express.Router()
, controllersRegistry = {};
var self = this;
if (!routes.routes) {
throw Error('Module: `' + moduleName + '`. No `routes` field in file: ' + colors.red(routesFile));
}
self.emit('twee.setupRoutes.Start', moduleName, prefix, router, controllersRegistry);
self.emit('twee.setupRoutes.GlobalModuleParams.Start', routes.params, router, moduleName);
// Install route global params
this.setupParams(routes.params, router, moduleName);
self.emit('twee.setupRoutes.GlobalModuleParams.End', routes.params, router, moduleName);
routes.routes.forEach(function(route){
var pattern = route.pattern || ''
, controllers = route.controllers || []
, middleware = route.middleware || {}
, params = route.params || {};
if (!pattern) {
throw Error('Module: `' + moduleName + '`. No valid `pattern` sat for route');
}
if (!controllers.length) {
return;
}
// If route has been disabled - then don't process it
if (route.disabled) {
return;
}
self.emit('twee.setupRoutes.ControllerParams.Start', params, router, moduleName);
// Installing params for each controller set
self.setupParams(params, router, moduleName);
self.emit('twee.setupRoutes.ControllerParams.End', params, router, moduleName);
controllers.forEach(function(controller) {
var controller_info = controller.split('.');
if (controller_info.length == 0 || !controller_info[0].trim()) {
throw new Error('Controller does not have controller name, action and method');
}
var controller_name = controller_info[0].trim()
, action_name = ''
, methods = [];
if (controller_info.length === 1) {
// trying indexAction
action_name = 'indexAction';
methods.push('all');
} else if (controller_info.length === 2) {
action_name = controller_info[1].trim();
methods.push('all');
} else if (controller_info.length === 3) {
action_name = controller_info[1].trim();
var _methods = controller_info[2].trim().split(',')
, at_least_one_method = false;
// Iterating for all the methods and call appropriate router
_methods.forEach(function(requestMethod){
if (router[requestMethod.trim()]) {
methods.push(requestMethod.trim());
at_least_one_method = true;
}
});