1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | const assert = require ('assert');
|
18 | const path = require ('path');
|
19 |
|
20 | const Loader = require ('./loader');
|
21 |
|
22 | const {
|
23 | stat,
|
24 | readdir
|
25 | } = require ('fs-extra');
|
26 |
|
27 | const {
|
28 | forOwn
|
29 | } = require ('lodash');
|
30 |
|
31 | const LegacyListener = require ('./messaging/legacy-listener');
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 | module.exports = Loader.extend ({
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 | app: null,
|
47 |
|
48 | init () {
|
49 | this._super.call (this, ...arguments);
|
50 |
|
51 | assert (!!this.app, "You must define the 'app' property");
|
52 | },
|
53 |
|
54 | load (opts) {
|
55 | let {dirname} = opts;
|
56 |
|
57 | assert (!!dirname, 'Your options must have a `dirname` property');
|
58 |
|
59 | return stat (dirname).then (stats => {
|
60 | return stats.isDirectory () ? readdir (dirname) : {};
|
61 | }).then (eventNames => {
|
62 |
|
63 |
|
64 |
|
65 | let promises = [];
|
66 | let listeners = {};
|
67 |
|
68 |
|
69 |
|
70 | eventNames.forEach (eventName => {
|
71 | const eventPath = path.join (dirname, eventName);
|
72 | promises.push (this._loadListenersFromPath (eventPath));
|
73 | });
|
74 |
|
75 |
|
76 |
|
77 | return Promise.all (promises).then (results => {
|
78 | eventNames.forEach ((eventName, i) => {
|
79 | let loaded = results[i];
|
80 | listeners[eventName] = loaded;
|
81 |
|
82 | forOwn (loaded, (listener, name) => {
|
83 | listener.name = name;
|
84 |
|
85 | this.app.on (eventName, listener);
|
86 | })
|
87 | });
|
88 |
|
89 | return listeners;
|
90 | });
|
91 | }).catch (err => {
|
92 | if (err.code && err.code === 'ENOENT')
|
93 | return {};
|
94 |
|
95 | return Promise.reject (err);
|
96 | });
|
97 | },
|
98 |
|
99 | _loadListenersFromPath (eventPath) {
|
100 | const app = this.app;
|
101 |
|
102 | return stat (eventPath).then (stats => {
|
103 | if (!stats.isDirectory ())
|
104 | return {};
|
105 |
|
106 | let loader = new Loader ();
|
107 |
|
108 | return loader.load ({
|
109 | dirname: eventPath,
|
110 | recursive: false,
|
111 | resolve (listener) {
|
112 |
|
113 |
|
114 |
|
115 | return listener.prototype && !!listener.prototype.handleEvent ? new listener ({app}) : new LegacyListener ({app, listener});
|
116 | }
|
117 | });
|
118 | });
|
119 | }
|
120 | });
|