Created
October 16, 2018 11:09
-
-
Save arsduo/103a68456a14ac1e99f1726e3b75ff42 to your computer and use it in GitHub Desktop.
Batched Elm Event Logger in JS
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
export default class MessageLogger { | |
constructor() { | |
this.eventQueue = []; | |
} | |
eventReceived(eventData) { | |
this.eventQueue.push(eventData); | |
} | |
uploadMessages() { | |
// use splice to ensure that we don't lose messages at the transition | |
const messagesToSend = this.eventQueue.splice(0, this.eventQueue.length); | |
if (messagesToSend.length == 0) { | |
return new Promise(() => {}); | |
} | |
const body = JSON.stringify({ events: messagesToSend }); | |
return fetch(`${yourServerURL}/logging`, { | |
body: body, | |
method: "POST" | |
}) | |
.then(response => { | |
if (!response.ok) { | |
// if the messages didn't make it, put them back on the queue at the front to preserve order | |
this.eventQueue.splice(0, 0, ...messagesToSend); | |
} | |
}) | |
.catch(() => { | |
// if the messages didn't make it, put them back on the queue at the front to preserve order | |
this.eventQueue.splice(0, 0, ...messagesToSend); | |
}); | |
} | |
startListening(ports, interval) { | |
ports.logEvent.subscribe(eventData => { | |
this.eventReceived(JSON.parse(eventData)); | |
}); | |
// send messages every 10 seconds | |
setInterval(() => this.uploadMessages(), interval || 10000); | |
// can't hurt to try | |
window.addEventListener("beforeunload", event => { | |
this.uploadMessages(); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment