yumechi-no-kuni/src/web/app/common/scripts/messaging-stream.js

43 lines
1.1 KiB
JavaScript
Raw Normal View History

2017-02-18 01:51:11 -06:00
const ReconnectingWebSocket = require('reconnecting-websocket');
const riot = require('riot');
class Connection {
constructor(me, otherparty) {
2017-02-18 17:09:38 -06:00
// BIND -----------------------------------
this.onOpen = this.onOpen.bind(this);
this.onMessage = this.onMessage.bind(this);
this.close = this.close.bind(this);
// ----------------------------------------
2017-02-18 01:51:11 -06:00
this.event = riot.observable();
this.me = me;
const host = CONFIG.api.url.replace('http', 'ws');
this.socket = new ReconnectingWebSocket(`${host}/messaging?i=${me.token}&otherparty=${otherparty}`);
this.socket.addEventListener('open', this.onOpen);
this.socket.addEventListener('message', this.onMessage);
}
onOpen() {
this.socket.send(JSON.stringify({
i: this.me.token
}));
}
onMessage(message) {
try {
2017-02-18 17:09:38 -06:00
const msg = JSON.parse(message.data);
if (msg.type) this.event.trigger(msg.type, msg.body);
2017-02-18 01:51:11 -06:00
} catch(e) {
// noop
}
}
close() {
this.socket.removeEventListener('open', this.onOpen);
this.socket.removeEventListener('message', this.onMessage);
}
}
module.exports = Connection;