Free javascript Hosting


widget-services.js

Uploaded on Feb 05 2022 02:08 by tjtremblay

/*
StatusDashboard Widget - Services
Copyright: 2021 Quinico Partners, LLC
*/

// Dashboard domain
const domain = 'mines-systemsummary.statusdashboard.com';

// Dashboard ID
const dashboard_id = '202'

// Number of records to return
const records = 1;

// Service listing settings
const statuses = {
0: {
'display': 'Operational',
'class': 'operational'
},
1: {
'display': 'Maintenance',
'class': 'maintenance'
},
2: {
'display': 'Incident',
'class': 'incident'
},
3: {
'display': 'Incident & Maintenance',
'class': 'both'
}
}

// Debug
const debug = false;

// Refresh rate
let interval = 30000;

// Server eTag
let eTag;

// Initialize the timer var
let intervalTimer;

// Paginators
let next;
let previous;

// Initial currentUrl is base Url
let currentUrl = `https://${domain}/api/v1/public/dashboard/?limit=${records}`;

// Log info
function log(message) {
// If debug logging is enabled, log the message
if (debug) {
var d = new Date().toLocaleString();
console.log(`${d}: ${message}`);
}
}

// Fetch the data from the StatusDashboard API and await the response
// before refreshing the widget.
async function getAPI(url) {
const response = await fetch(
url, {
headers: {
'If-None-Match': eTag
}
}
);

log(`StatusDashboard Widget: Fetch response status code: ${response.status}.`);
// Content not modified, do not update the page
// Note the use here of HTTP204 (no content) vs a more
// appropriate HTTP304 (not modified). Required by circumstances.
if (response.status == 204) {
// Hide the loading spinner
document.getElementById('sd-spinner').style.display = 'none';
// Throw an error to stop processing - no page update should occur
throw new Error('HTTP204 no content (taken as HTTP304)');
// Content modified, return and update the page
} else if (response.status == 200) {
// Get the server eTag
const response_etag = response.headers.get('etag').replace(/^"|"$/g, '');
log(`StatusDashboard Widget: Fetch response eTag: ${response_etag}.`);
// Set the global eTag
eTag = response_etag;
// Get the JSON data and send it back
const data = await response.json();
return data
// An unknown error occurred
} else {
throw new Error(`Error fetching API content: ${response.status}`);
}
}

// Refresh the widget: called on page load, and whenever 'next' or 'previous' are called
function refresh(url) {

// If the browser or tab is not active, do not make an API call
if (document.hidden) {
log(`StatusDashboard Widget: Page not active, not fetching Url.`);
return;
}

log(`StatusDashboard Widget: Refreshing data from Url: ${url}.`);

// Show the loading spinner
document.getElementById('sd-spinner').style.display = 'block';

// Get the data from the API and build the <ul> element.
getAPI(url).then(data => {
// Create the ul
let ul = '<ul class="sd-list-group">';
// Build a <ul> element for each service returned from the API
for (i = 0; i < data.objects.length; i++) {
ul += `<li class="sd-list-group-item sd-flex sd-justify-content-between sd-align-items-center">${data.objects[i]['name']}<span class="sd-badge ${statuses[data.objects[i]['status']]['class']}">${statuses[data.objects[i]['status']]['display']}</span></li>`;
}
// Close the ul
ul += '</ul>';

// Update the status container with the refreshed <ul> element
document.getElementById('sd-status-container').innerHTML = ul;

// The page is updated, hide the spinner
document.getElementById('sd-spinner').style.display = 'none';

// If there's a next/previous, set the navigation links to whatever
// the API returned. If the respective link is null, then hide the navigation link
if (data.meta['next']) {
log(`StatusDashboard Widget: Next = ${data.meta['next']}.`);
next = `https://${domain}${data.meta['next']}`;
document.getElementById('sd-next').style.display = 'inline-block';
} else {
// There are no next records, so set next to undefined and hide the associated navigational element
next = null;
document.getElementById('sd-next').style.display = 'none';
}
if (data.meta['previous']) {
log(`StatusDashboard Widget: Previous = ${data.meta['previous']}.`);
previous = `https://${domain}${data.meta['previous']}`;
document.getElementById('sd-previous').style.display = 'inline-block';
} else {
// There are no previous records, so set previous to undefined and hide the associated navigational element
previous = null;
document.getElementById('sd-previous').style.display = 'none';
}
log('StatusDashboard Widget: getAPI exit.');
})
.catch(error => {
log(`StatusDashboard Widget: Error fetching status: ${error}.`);
});
}

// Insert the CSS
const sdCssExists = document.getElementById('sd-css');
if (sdCssExists == null) {
log('StatusDashboard Widget: Adding CSS.');
const css = document.createElement("link");
css.type = "text/css";
css.id = "sd-css";
css.rel = "stylesheet";
css.href = `https://${domain}/st/css/widgets/${dashboard_id}/widget-services.css`;
document.getElementsByTagName('head')[0].appendChild(css);
} else {
log('StatusDashboard Widget: CSS exists.');
}

// Create a div container to hold the widget
const container = document.createElement('div');
container.id = 'sd-main-container';
container.innerHTML = `
<div id="sd-header-row">
<div id="sd-spinner" class="sd-spinner"></div>
<a id="sd-previous"><span class="chevron left" title="Previous results"></span></a>
<a id="sd-next"><span class="chevron right" title="Next results"></span></a>
</div>
<div id="sd-status-container">
</div>
<div id="sd-db-link">Visit our <a href="https://mines.statusdashboard.com" target="_blank">Detailed StatusDashboard for More Information</a></div>
</div>
`;
// Insert the container directly before the script execution location
const sd_script = document.getElementById('sd-widget');
const parent = sd_script.parentNode;
parent.insertBefore(container, sd_script.nextSibling);

// Register the click handlers
// 'next' and 'previous' will get updated on every API call
document.getElementById('sd-next').onclick=function() {
// Stop the timer
clearInterval(intervalTimer);
// Store the current Url
currentUrl = next;
log(`StatusDashboard Widget: Next clicked with next Url: ${currentUrl}.`);
// Refresh the data
refresh(currentUrl);
// Restart the timer
log(`StatusDashboard Widget: Starting timer on Url: ${currentUrl}.`);
intervalTimer = setInterval('refresh(`${currentUrl}`);', interval);
};
document.getElementById('sd-previous').onclick=function() {
// Stop the timer
clearInterval(intervalTimer);
// Store the current Url
currentUrl = previous;
log(`StatusDashboard Widget: Previous clicked with previous Url: ${currentUrl}.`);
// Refresh the data
refresh(currentUrl);
// Restart the timer
log(`StatusDashboard Widget: Starting timer on Url: ${currentUrl}.`);
intervalTimer = setInterval('refresh(`${currentUrl}`);', interval);
};

// Refresh the widget on initial page load
refresh(currentUrl);

// Start the timer
intervalTimer = setInterval('refresh(`${currentUrl}`);', interval);

Back to list