1 | var fs = require('fs'),
|
2 | exists = require('fs-exists-sync'),
|
3 | path = require('path')
|
4 |
|
5 |
|
6 | module.exports = class {
|
7 |
|
8 | constructor(config, paths) {
|
9 | paths = paths;
|
10 | this.events = [];
|
11 |
|
12 | var files = this.loadFiles();
|
13 |
|
14 | for(var key in files){
|
15 | this.events.push(require(files[key])({config, paths}));
|
16 | }
|
17 |
|
18 | return this;
|
19 | }
|
20 |
|
21 | loadFiles() {
|
22 | var files = [];
|
23 |
|
24 | if (exists(paths.app.middleware)) {
|
25 | fs.readdirSync(paths.app.middleware)
|
26 | .filter(function (file) {
|
27 | return (file.indexOf(".") !== 0 && path.extname(file) == ".js");
|
28 | })
|
29 | .forEach(function (file) {
|
30 | files.push(path.join(paths.app.middleware, file));
|
31 | });
|
32 | }
|
33 |
|
34 | return files;
|
35 | }
|
36 |
|
37 | exists(name){
|
38 | for(var key in this.events){
|
39 | if(this.events[key][name]){
|
40 | return true
|
41 | }
|
42 | }
|
43 |
|
44 | return false;
|
45 | }
|
46 |
|
47 | emit(eventName, options){
|
48 | var events = (name, options, key = 0) => {
|
49 | for(var i = key; i < this.events.length; i++){
|
50 | if(this.events[i][name]){
|
51 | return this.events[i][name](options, (returns) => {
|
52 | return events(name, returns, ++i)
|
53 | })
|
54 | }
|
55 | }
|
56 |
|
57 | return options;
|
58 | }
|
59 |
|
60 | return events(eventName, options);
|
61 | }
|
62 |
|
63 | }
|