Last active
August 16, 2020 03:34
-
-
Save PedroGutierrezStratio/98a2c6d5298ec92e64ef to your computer and use it in GitHub Desktop.
Drawing the MongoDB's data with Chart.js through WebSockets.
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
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> | |
<div style="margin: 20px;display: block;"> | |
<canvas style="width: 600px; height: 300px" id="chart"></canvas> | |
</div> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js"></script> | |
<script> | |
var ws = new WebSocket('ws://127.0.0.1:8008/'); | |
var data = {}; | |
ws.onmessage = function(response){ | |
var responseData = JSON.parse(response.data); | |
responseData | |
.map(function(row){ | |
row.hour = new Date(row.hour).toISOString().slice(0, 16).replace('T',' '); | |
return row; | |
}) | |
.forEach(function(row){ | |
if(!data[row.country]){ | |
data[row.country] = {}; | |
} | |
data[row.country][row.hour] = row.count; | |
}); | |
drawChart(); | |
} | |
var chart = new Chart(document.getElementById('chart').getContext('2d')); | |
var chartLine; | |
function drawChart(){ | |
if(chartLine){ | |
chartLine.destroy(); | |
} | |
var palette = ['#CDA7C6','#7C7D9A','#8FBCCC']; | |
var chartData = { | |
labels: [], | |
datasets: [] | |
}; | |
for(var country in data){ | |
var hours = data[country]; | |
var counts = Object.keys(hours).map(function(x){return hours[x];}); | |
var color = palette.pop(); | |
var dataset = { | |
label: country, | |
data: counts, | |
pointColor: color, | |
strokeColor: color, | |
pointStrokeColor: '#fff', | |
fillColor: "transparent", | |
}; | |
if(chartData.labels.length < Object.keys(hours).length){ | |
chartData.labels = Object.keys(hours); | |
} | |
chartData.datasets.push(dataset); | |
} | |
chartLine = chart.Line(chartData); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wow