Browse Source

update app.js for reconnect

Ben Allen 1 tuần trước cách đây
mục cha
commit
337ee0d1d4
2 tập tin đã thay đổi với 22 bổ sung2 xóa
  1. 3 0
      config.yaml
  2. 19 2
      static/app.js

+ 3 - 0
config.yaml

@@ -20,3 +20,6 @@ monitors:
   - name: Example API
     url: https://httpbin.org/status/200
     category: API
+  # - name: Example Fail
+  #   url: https://httpbin.org/status/500
+  #   category: API

+ 19 - 2
static/app.js

@@ -8,6 +8,8 @@ const modalGrid = document.getElementById("service-modal-grid");
 const services = new Map();
 const tiles = new Map();
 let openServiceName = "";
+let socket = null;
+let reconnectTimer = 0;
 
 function formatTimestamp(value) {
   const date = new Date(value);
@@ -200,11 +202,25 @@ function upsertService(service) {
   }
 }
 
+function scheduleReconnect() {
+  if (reconnectTimer) {
+    return;
+  }
+
+  reconnectTimer = window.setTimeout(function() {
+    reconnectTimer = 0;
+    connectWebSocket();
+  }, 2000);
+}
+
 function connectWebSocket() {
   const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
-  const socket = new WebSocket(protocol + "//" + window.location.host + "/ws");
+  socket = new WebSocket(protocol + "//" + window.location.host + "/ws");
 
   socket.addEventListener("open", function() {
+    loadInitialStatus().catch(function(error) {
+      console.error("Failed to reload status after websocket reconnect:", error);
+    });
   });
 
   socket.addEventListener("message", function(event) {
@@ -216,7 +232,8 @@ function connectWebSocket() {
   });
 
   socket.addEventListener("close", function() {
-    window.setTimeout(connectWebSocket, 2000);
+    socket = null;
+    scheduleReconnect();
   });
 
   socket.addEventListener("error", function() {