This commit is contained in:
syuilo 2017-02-18 16:51:11 +09:00
parent f9058cb739
commit 1d3f44b0fd
3 changed files with 37 additions and 35 deletions

View File

@ -15,7 +15,7 @@ module.exports = (me) ~>
signout: require './scripts/signout.js'
riot.mixin \messaging-stream do
MessagingStreamConnection: require './scripts/messaging-stream.ls'
MessagingStreamConnection: require './scripts/messaging-stream'
riot.mixin \is-promise do
is-promise: require './scripts/is-promise.ls'

View File

@ -0,0 +1,36 @@
const ReconnectingWebSocket = require('reconnecting-websocket');
const riot = require('riot');
class Connection {
constructor(me, otherparty) {
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 {
const message = JSON.parse(message.data);
if (message.type) this.event.trigger(message.type, message.body);
} catch(e) {
// noop
}
}
close() {
this.socket.removeEventListener('open', this.onOpen);
this.socket.removeEventListener('message', this.onMessage);
}
}
module.exports = Connection;

View File

@ -1,34 +0,0 @@
# Stream
#================================
ReconnectingWebSocket = require 'reconnecting-websocket'
riot = require 'riot'
class Connection
(me, otherparty) ~>
@event = riot.observable!
@me = me
host = CONFIG.api.url.replace \http \ws
@socket = new ReconnectingWebSocket "#{host}/messaging?i=#{me.token}&otherparty=#{otherparty}"
@socket.add-event-listener \open @on-open
@socket.add-event-listener \message @on-message
on-open: ~>
@socket.send JSON.stringify do
i: @me.token
on-message: (message) ~>
try
message = JSON.parse message.data
if message.type?
@event.trigger message.type, message.body
catch
# ignore
close: ~>
@socket.remove-event-listener \open @on-open
@socket.remove-event-listener \message @on-message
@socket.close!
module.exports = Connection