-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmedi.js
123 lines (94 loc) · 2.98 KB
/
medi.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
"use strict";
const medi = function medi(opts = { log:false }) {
const channels = {};
const shouldLog = opts.log;
const log = {
info() {
if (!shouldLog)
return;
return console.info(...arguments);
},
warn() {
if (!shouldLog)
return;
return console.warn(...arguments);
}
};
const matchesFilter = function(filter, match) {
const keys = Object.keys(match);
for (let key of keys) {
if (match[key] !== filter[key] || !(key in filter)) {
return false;
}
}
return true;
};
const getFirstAndOrSecondArgs = function(args) {
if (args.length === 1) {
return [args[0], null];
}
return [args[1], args[0]];
};
return {
when(channel, ...args) {
if (!channels[channel]) {
channels[channel] = [];
}
const [handler, filter] = getFirstAndOrSecondArgs(args);
channels[channel].push({ filter, handler });
return this;
},
emit(channel, ...args) {
if (!channels[channel]) {
log.warn(`Emit(): No handlers for event "${channel}", args: `, ...args);
return;
}
const [payload, filter] = getFirstAndOrSecondArgs(args);
log.info(`Emit(): Emitting event "${channel}" with payload:`, payload, 'and filter: ', filter);
const promises = [];
channels[channel].filter(({ filter: toMatch }) => {
// If we call a channel that has a filter without specifing a filter: abort.
if (!filter && toMatch) {
log.warn(`Emit(): Not calling channel "${ channel }", channel has a filter; no filter given`);
return false;
}
// If we call a channel that has a filter but the given filter does not match: abort.
if (filter && !(toMatch && matchesFilter(filter, toMatch))) {
log.warn(`Emit(): Not calling channel "${ channel }", given filter does not match channel's filter`);
return false;
}
return true;
}).forEach(({ handler }) => {
// Call each handler; resolve the result if something other than nothing was returned.
const result = handler(payload);
if (result !== undefined) {
promises.push(result);
}
});
return Promise.all(promises);
},
delete(channel, handler=null) {
if (!channels[channel]) {
log.warn(`Delete(): No handlers for channel "${channel}"; nothing to delete`);
return false;
}
if (!handler) {
delete channels[channel];
return this;
}
const index = channels[channel].findIndex(({ handler: channelHandler }) => {
if (channelHandler === handler) {
return true;
}
return false;
});
if (index === -1) {
console.warn(`Delete(): Given handler does not exists on channel "${channel}"`);
return false;
}
channels[channel].splice(index, 1);
return this;
}
};
};
export default medi;