Skip to content

Commit

Permalink
[-] updated the JS in sample app to be modular, cleaner
Browse files Browse the repository at this point in the history
  • Loading branch information
bnkamalesh committed Mar 13, 2022
1 parent 8174d06 commit f4bb376
Showing 1 changed file with 50 additions and 10 deletions.
60 changes: 50 additions & 10 deletions cmd/static/js/main.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,47 @@
const webgo = async () => {
const sse = (url, config = {}) => {
const {
onMessage,
onError,
initialBackoff = 10, // milliseconds
maxBackoff = 15 * 1000, // 15 seconds
backoffStep = 50, // milliseconds
} = config;

let backoff = initialBackoff,
sseRetryTimeout = null;

const start = () => {
const source = new EventSource(url);
source.onopen = () => {
// reset backoff to initial, so further failures will again start with initial backoff
// instead of previous duration
backoff = initialBackoff;
};

source.onmessage = (event) => {
onMessage && onMessage(event);
};

source.onerror = (err) => {
source.close();
clearTimeout(sseRetryTimeout);
// reattempt connecting with *linear* backoff
sseRetryTimeout = window.setTimeout(() => {
start(url, onMessage);
if (backoff < maxBackoff) {
backoff += backoffStep;
if (backoff > maxBackoff) {
backoff = maxBackoff;
}
}
}, backoff);
onError && onError(err);
};
};
return start;
};

const clientID = Math.random()
.toString(36)
.replace(/[^a-z]+/g, "")
Expand All @@ -7,23 +50,20 @@ const webgo = async () => {
const sseClientsDOM = document.getElementById("sse-clients");
const sseClientIDDOM = document.getElementById("sse-client-id");

const startSSE = (clientID) => {
const source = new EventSource(`/sse/${clientID}`);
source.onmessage = function (event) {
sse(`/sse/${clientID}`, {
onMessage: (event) => {
const parts = event.data?.split("(");
const date = new Date(parts[0]);
const activeClients = parts[1].replace(")", "");
sseDOM.innerText = date.toLocaleString();
sseClientsDOM.innerText = activeClients;
sseClientIDDOM.innerText = clientID;
};
source.onerror = (err) => {
source.close();
},
onError: (err) => {
console.log(err);
sseDOM.innerText = `SSE error, restarting`;
startSSE(clientID);
};
};
startSSE(clientID);
},
backoffStep: 150,
})();
};
webgo();

0 comments on commit f4bb376

Please sign in to comment.