Skip to content

Instantly share code, notes, and snippets.

@PedroGutierrezStratio
Last active August 16, 2020 03:34
Show Gist options
  • Save PedroGutierrezStratio/98a2c6d5298ec92e64ef to your computer and use it in GitHub Desktop.
Save PedroGutierrezStratio/98a2c6d5298ec92e64ef to your computer and use it in GitHub Desktop.
Drawing the MongoDB's data with Chart.js through WebSockets.
<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>
@yungwarlock
Copy link

Wow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment