Forked from migajek/gist:dede8e9184a087e19bd9
Last active
September 11, 2015 16:52
-
-
Save jklemmack/09957fb0e05cf13181cd to your computer and use it in GitHub Desktop.
Angular + ServiceStack's SSE
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
factory('sse', ['$rootScope', '$http', function($rootScope, $http) { | |
// https://gist.github.com/migajek | |
var splitOnFirst = function (s, c) { if (!s) return [s]; var pos = s.indexOf(c); return pos >= 0 ? [s.substring(0, pos), s.substring(pos + 1)] : [s]; }; | |
return { | |
start: function(handlers) { | |
var opt = {}; | |
var sse = new EventSource('/event-stream'); | |
sse.addEventListener('message', function(e) { | |
var parts = splitOnFirst(e.data, ' '); | |
var selector = parts[0]; | |
var msg = parts[1] ? parts[1].trim() : null; | |
if (msg && msg.indexOf("{") == 0 && msg.indexOf("}") == msg.length-1) | |
msg = JSON.parse(msg); | |
else | |
msg = msg.replace(/^"(.*)"$/, "$1").replace(/\\"/g, '"'); | |
parts = splitOnFirst(selector, '.'); | |
var handled = false; | |
var cmd = ""; | |
// currently handles only cmd.OnConnect | |
if (parts.length > 1 && parts[0] == "cmd") | |
{ | |
cmd = parts[1]; | |
if (cmd == "onConnect") | |
{ | |
if (angular.isObject(msg)) | |
angular.extend(opt, msg); | |
if (opt.heartbeatUrl) { | |
if (opt.heartbeat) { | |
window.clearInterval(opt.heartbeat); | |
} | |
opt.heartbeat = window.setInterval(function () { | |
$http.post(opt.heartbeatUrl, null, function(r) {}); | |
}, parseInt(opt.heartbeatIntervalMs) || 1000); | |
} | |
if (opt.unRegisterUrl) { | |
if ((!('unregisterWhenStateChange' in opt)) || (opt.unregisterWhenStateChange)) | |
{ | |
var stopHeartBeatAndUnregister = function () { | |
if (opt.heartbeat) { | |
window.clearInterval(opt.heartbeat); | |
} | |
sse.close(); | |
$http.post(opt.unRegisterUrl, null, function(r) {}); | |
} | |
var deregUI = $rootScope.$on('$stateChangeStart', function(){ | |
stopHeartBeatAndUnregister(); | |
deregUI(); | |
}); | |
var deregRouter = $rootScope.$on('$routeChangeStart', function(){ | |
stopHeartBeatAndUnregister(); | |
deregRouter(); | |
}); | |
} | |
} | |
} | |
} | |
var key = selector in handlers ? selector : (cmd in handlers ? cmd : false); | |
if (key) | |
{ | |
$rootScope.$apply(function () { | |
handlers[key].apply(sse, [msg]); | |
}); | |
} | |
}); | |
} | |
}; | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment