summaryrefslogtreecommitdiff
path: root/ext/fg/js/frontend-api-receiver.js
diff options
context:
space:
mode:
authortoasted-nutbread <toasted-nutbread@users.noreply.github.com>2020-05-02 12:50:44 -0400
committerGitHub <noreply@github.com>2020-05-02 12:50:44 -0400
commit6c341a13d813fc63b76fbbffe7920eeaf116d3a8 (patch)
treedf6f10e3e68bd22e50731af94fe5de328fe2a1da /ext/fg/js/frontend-api-receiver.js
parentcae6b657ab418a1cafedcb1cf72d0e793fa5178b (diff)
Refactor frontend API classes (#482)
* Mark functions as private * Remove constructor side effects * Use safer handler invocation * Mark functions as private * Mark fields as private * Update BackendApiForwarder public API
Diffstat (limited to 'ext/fg/js/frontend-api-receiver.js')
-rw-r--r--ext/fg/js/frontend-api-receiver.js32
1 files changed, 18 insertions, 14 deletions
diff --git a/ext/fg/js/frontend-api-receiver.js b/ext/fg/js/frontend-api-receiver.js
index 4abd4e81..c5bb58af 100644
--- a/ext/fg/js/frontend-api-receiver.js
+++ b/ext/fg/js/frontend-api-receiver.js
@@ -20,38 +20,42 @@ class FrontendApiReceiver {
constructor(source='', handlers=new Map()) {
this._source = source;
this._handlers = handlers;
+ }
- chrome.runtime.onConnect.addListener(this.onConnect.bind(this));
+ prepare() {
+ chrome.runtime.onConnect.addListener(this._onConnect.bind(this));
}
- onConnect(port) {
+ _onConnect(port) {
if (port.name !== 'frontend-api-receiver') { return; }
- port.onMessage.addListener(this.onMessage.bind(this, port));
+ port.onMessage.addListener(this._onMessage.bind(this, port));
}
- onMessage(port, {id, action, params, target, senderId}) {
+ _onMessage(port, {id, action, params, target, senderId}) {
if (target !== this._source) { return; }
const handler = this._handlers.get(action);
if (typeof handler !== 'function') { return; }
- this.sendAck(port, id, senderId);
+ this._sendAck(port, id, senderId);
+ this._invokeHandler(handler, params, port, id, senderId);
+ }
- handler(params).then(
- (result) => {
- this.sendResult(port, id, senderId, {result});
- },
- (error) => {
- this.sendResult(port, id, senderId, {error: errorToJson(error)});
- });
+ async _invokeHandler(handler, params, port, id, senderId) {
+ try {
+ const result = await handler(params);
+ this._sendResult(port, id, senderId, {result});
+ } catch (error) {
+ this._sendResult(port, id, senderId, {error: errorToJson(error)});
+ }
}
- sendAck(port, id, senderId) {
+ _sendAck(port, id, senderId) {
port.postMessage({type: 'ack', id, senderId});
}
- sendResult(port, id, senderId, data) {
+ _sendResult(port, id, senderId, data) {
port.postMessage({type: 'result', id, senderId, data});
}
}