forked from mozilla-extensions/firefox-voice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommunicate.js
More file actions
44 lines (41 loc) · 1.14 KB
/
Copy pathcommunicate.js
File metadata and controls
44 lines (41 loc) · 1.14 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
/* globals log */
this.communicate = (function() {
const exports = {};
const HANDLERS = {};
exports.register = function(type, handler, noConflict = false) {
if (!noConflict && HANDLERS[type]) {
throw new Error(`There is already a handler registered for ${type}`);
}
HANDLERS[type] = handler;
};
exports.handle = async function(script, message, sender) {
log.messaging(`${script}->`, JSON.stringify(message));
if (!HANDLERS[message.type]) {
log.warn(
"Message of unknown type:",
String(message.type),
JSON.stringify(message)
);
throw new Error(`No handler for ${message.type}`);
}
try {
return Promise.resolve(HANDLERS[message.type](message, sender));
} catch (e) {
log.error(`Error in ${message.type} handler: ${e}`, e.stack);
const response = {
status: "error",
message: String(e),
name: e.name,
stack: e.stack,
reason: e.reason,
};
for (const name in e) {
if (!(name in response)) {
response[name] = e[name];
}
}
return response;
}
};
return exports;
})();