[fix] Connect to WebSocket route before every API call

This commit is contained in:
kload 2014-05-25 10:21:28 +00:00
parent 9215420093
commit 3fc7599a99

View file

@ -93,31 +93,23 @@ app = Sammy('#main', function (sam) {
});
},
// Websocket connection
websocket: function(callback) {
// API call
api: function(uri, callback, method, data) {
c = this;
if (store.get('connected')) {
c.ws = new WebSocket('wss://'+ store.get('url') +'/messages');
c.ws.onmessage = function(evt) {
// Open a WebSocket connection to retrieve live messages from the moulinette
ws = new WebSocket('wss://'+ store.get('url') +'/messages');
ws.onmessage = function(evt) {
console.log(evt.data);
$.each($.parseJSON(evt.data), function(k, v) {
c.flash(k, v);
});
}
c.ws.onopen = function() {
if (typeof callback === 'function') {
callback();
}
}
c.ws.onclose = function() {
delete c.ws;
}
}
},
// API connection helper
api: function (uri, callback, method, data) {
c = this;
// If not connected, WebSocket connection will raise an error, but we do not want to interrupt API request
ws.onerror = ws.onopen;
ws.onopen = function(evt) {
method = typeof method !== 'undefined' ? method : 'GET';
data = typeof data !== 'undefined' ? data : {};
if (window.navigator && window.navigator.language && (typeof data.locale === 'undefined')) {
@ -247,6 +239,7 @@ app = Sammy('#main', function (sam) {
store.clear('slide');
c.redirect(store.get('path-1'));
});
}
},
// Render view (cross-browser)
@ -396,7 +389,6 @@ app = Sammy('#main', function (sam) {
}
c.api('/login', function(data) {
store.set('connected', true);
c.websocket();
$('.logout-button').fadeIn();
c.flash('success', y18n.t('logged_in'));
@ -1079,9 +1071,6 @@ app = Sammy('#main', function (sam) {
});
sam.websocket();
});