1
0
forked from MTSR/mapserver
mapserver/public/js/WebSocketChannel.js

74 lines
1.5 KiB
JavaScript
Raw Normal View History

2019-01-29 20:08:54 +03:00
import { getStats } from './api.js';
2019-06-11 16:01:16 +03:00
class WebSocketChannel {
constructor(){
this.wsUrl = window.location.protocol.replace("http", "ws") +
"//" + window.location.host +
window.location.pathname.substring(0, window.location.pathname.lastIndexOf("/")) +
"/api/ws";
2019-04-04 11:19:29 +03:00
2019-06-11 16:01:16 +03:00
this.listenerMap = {/* type -> [listeners] */};
2019-02-01 14:58:26 +03:00
}
2019-01-29 20:08:54 +03:00
2019-06-11 16:01:16 +03:00
addListener(type, listener){
var list = this.listenerMap[type];
if (!list){
list = [];
this.listenerMap[type] = list;
}
2019-01-29 20:08:54 +03:00
2019-06-11 16:01:16 +03:00
list.push(listener);
2019-02-03 20:18:14 +03:00
}
2019-06-11 16:01:16 +03:00
removeListener(type, listener){
var list = this.listenerMap[type];
if (!list){
return;
}
2019-01-29 20:08:54 +03:00
2019-06-11 16:01:16 +03:00
this.listenerMap[type] = list.filter(l => l != listener);
}
2019-01-29 20:08:54 +03:00
2019-06-11 16:01:16 +03:00
connect(){
var ws = new WebSocket(this.wsUrl);
var self = this;
ws.onmessage = function(e){
var event = JSON.parse(e.data);
//rendered-tile, mapobject-created, mapobjects-cleared
var listeners = self.listenerMap[event.type];
if (listeners){
listeners.forEach(function(listener){
listener(event.data);
});
}
};
function fallbackPolling(){
getStats()
.then(function(stats){
if (!stats){
// no stats (yet)
return;
}
var listeners = self.listenerMap["minetest-info"];
if (listeners){
listeners.forEach(function(listener){
listener(stats);
});
}
});
}
2019-06-11 16:01:16 +03:00
ws.onerror = function(){
//fallback to polling stats
setInterval(fallbackPolling, 2000);
2019-06-11 16:01:16 +03:00
};
}
}
2019-01-29 20:08:54 +03:00
2019-06-11 16:01:16 +03:00
export default new WebSocketChannel();