-
-
Save cAstraea/9e6807e24bbaa1c82c9cbacba5166f2b to your computer and use it in GitHub Desktop.
Drawing the MongoDB's data with Chart.js through WebSockets.
This file contains hidden or 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