Created
February 16, 2019 19:57
-
-
Save mpapec/779ec6c5d13045ff725028df344ba9df to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var EventSourceWrapper = (function() { | |
"use strict;" | |
var Class = function (url) { | |
var that = this; | |
that.ws = undefined; | |
that.connected = false; | |
that.reconnect = 3 *1000; | |
that.log = undefined; | |
// that.log = function(msg) { console.log(msg); }; | |
that.events = {}; | |
var _onmessage = function (event) { | |
// | |
var res = JSON.parse(event.data).data; | |
if (!res.length) return; | |
if (that.events.message) { that.events.message(res); } | |
if (that.log) { | |
that.log('Message received: '+ url); | |
that.log(res); | |
} | |
if (!Array.isArray(res)) { | |
that.log && that.log("Not an array, skipping"); | |
return; | |
} | |
for (var i =0; i <res.length; i++) { | |
var eventStr = res[i]; | |
if (typeof eventStr !== 'string') continue; | |
var msg = res[++i]; | |
var callback = that.events[eventStr]; | |
if (!callback) { | |
that.log && that.log("No event handler for "+ eventStr); | |
continue; | |
} | |
callback(msg); | |
} | |
}; | |
var nthConnect = 0; | |
var _onopen = function () { | |
that.log && that.log('Connection opened: '+ url); | |
that.connected = true; | |
// | |
if (that.events.connect) { that.events.connect(nthConnect); } | |
nthConnect++; | |
}; | |
var _onerror = function () { | |
that.log && that.log('Connection error: '+ url); | |
that.connected = false; | |
if (that.reconnect) { | |
setTimeout(function(){ | |
that.log && that.log('Reconnecting: '+ url); | |
_start(); | |
}, that.reconnect); | |
} | |
}; | |
var _start = function () { | |
// | |
that.ws && that.ws.close(); | |
that.ws = new EventSource(url); | |
that.ws.onmessage = _onmessage; | |
that.ws.onopen = _onopen; | |
that.ws.onerror = _onerror; | |
}; | |
_start(); | |
// | |
that.on = function (eventStr, callback) { | |
that.events[eventStr] = callback; | |
return that; | |
}; | |
}; | |
return function (myurl, query) { | |
return new Class(myurl + btoa(JSON.stringify(query))); | |
}; | |
}()); | |
var query = { | |
"v": 3, "q": { "find": {} } | |
} | |
var bitsocket = EventSourceWrapper("https://genesis.bitdb.network/s/1FnauZ9aUH2Bex6JzdcV4eNX7oLSSEbxtN/", query); | |
bitsocket.on("message", function(msg){ | |
console.log(msg); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment