mirror of
https://git.ianrenton.com/ian/spothole.git
synced 2026-02-04 09:14:30 +00:00
Use SSE frontend #3
This commit is contained in:
@@ -1,3 +1,6 @@
|
||||
// SSE event source
|
||||
let evtSource;
|
||||
|
||||
// Load spots and populate the table.
|
||||
function loadSpots() {
|
||||
$.getJSON('/api/v1/spots' + buildQueryString(), function(jsonData) {
|
||||
@@ -8,9 +11,36 @@ function loadSpots() {
|
||||
spots = jsonData;
|
||||
// Update table
|
||||
updateTable();
|
||||
// Start SSE connection to fetch updates in the background
|
||||
restartSSEConnection();
|
||||
});
|
||||
}
|
||||
|
||||
// Start an SSE connection (closing an existing one if it exists). This will then be used to add to the table on the
|
||||
// fly.
|
||||
function restartSSEConnection() {
|
||||
if (evtSource != null) {
|
||||
evtSource.close();
|
||||
}
|
||||
evtSource = new EventSource('/api/v1/spots/stream');
|
||||
|
||||
evtSource.onmessage = function(event) {
|
||||
// Store last updated time
|
||||
lastUpdateTime = moment.utc();
|
||||
updateRefreshDisplay();
|
||||
// Add spot to table
|
||||
newSpot = JSON.parse(event.data);
|
||||
console.log(newSpot);
|
||||
spots.unshift(newSpot);
|
||||
spots = spots.slice(0, -1);
|
||||
updateTable();
|
||||
};
|
||||
|
||||
evtSource.onerror = function(err) {
|
||||
setTimeout(restartSSEConnection(), 1000);
|
||||
};
|
||||
}
|
||||
|
||||
// Build a query string for the API, based on the filters that the user has selected.
|
||||
function buildQueryString() {
|
||||
var str = "?";
|
||||
@@ -316,9 +346,8 @@ function loadOptions() {
|
||||
$("#add-spot-button").show();
|
||||
}
|
||||
|
||||
// Load spots and set up the timer
|
||||
// Load spots (this will also set up the SSE connection to update them too)
|
||||
loadSpots();
|
||||
setInterval(loadSpots, REFRESH_INTERVAL_SEC * 1000);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -384,8 +413,6 @@ function displayIntroBox() {
|
||||
$(document).ready(function() {
|
||||
// Call loadOptions(), this will then trigger loading spots and setting up timers.
|
||||
loadOptions();
|
||||
// Update the refresh timing display every second
|
||||
setInterval(updateRefreshDisplay, 1000);
|
||||
// Display intro box
|
||||
displayIntroBox();
|
||||
});
|
||||
Reference in New Issue
Block a user