From adceb228dfdc9f4b93fbd6fa08a09bf2c4ce6129 Mon Sep 17 00:00:00 2001 From: Anton Roslund Date: Fri, 28 Mar 2025 17:15:34 +0100 Subject: [PATCH] refactor messagesChart.js --- static/js/status/messagesChart.js | 47 ++++++++++++++----------------- 1 file changed, 21 insertions(+), 26 deletions(-) diff --git a/static/js/status/messagesChart.js b/static/js/status/messagesChart.js index 4223016..a49e186 100644 --- a/static/js/status/messagesChart.js +++ b/static/js/status/messagesChart.js @@ -1,21 +1,21 @@ -const canvas = document.getElementById('messagesChart'); -const ctx = canvas.getContext('2d'); +async function messagesStatsGraph() { + const canvas = document.getElementById('messagesChart'); + const ctx = canvas.getContext('2d'); -// Show "Loading..." message -ctx.font = '16px Arial'; -ctx.fillStyle = 'gray'; -ctx.textAlign = 'center'; -ctx.fillText('Loading data...', canvas.width / 2, canvas.height / 2); + // Show "Loading..." message + ctx.font = '16px Arial'; + ctx.fillStyle = 'gray'; + ctx.textAlign = 'center'; + ctx.fillText('Loading data...', canvas.width / 2, canvas.height / 2); -fetch('https://map.sthlm-mesh.se/api/v1/messages-per-hour') - .then(response => response.json()) - .then(data => { + + try { + const response = await fetch('https://map.sthlm-mesh.se/api/v1/messages-per-hour') + const data = await response.json(); + const labels = data.map(entry => entry.hour); const counts = data.map(entry => entry.count); - // Clear the canvas before drawing the chart - ctx.clearRect(0, 0, canvas.width, canvas.height); - new Chart(ctx, { type: 'bar', data: { @@ -39,23 +39,18 @@ fetch('https://map.sthlm-mesh.se/api/v1/messages-per-hour') autoSkip: false } }, - y: { - beginAtZero: true - } - }, - plugins: { - legend: { - display: false // Hides the dataset label - } + y: { beginAtZero: true } }, + plugins: { legend: { display: false } }, } }); - }) - .catch(error => { + } catch(error) { console.error('Error fetching data:', error); - - // Clear the canvas before showing an error message ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = 'red'; ctx.fillText('Error loading data', canvas.width / 2, canvas.height / 2); - }); + } +} + + +messagesStatsGraph(); \ No newline at end of file