Skip to content

Instantly share code, notes, and snippets.

@ijokarumawak
Last active August 29, 2015 14:20
Show Gist options
  • Save ijokarumawak/c2d7d47da0d8bf6812dd to your computer and use it in GitHub Desktop.
Save ijokarumawak/c2d7d47da0d8bf6812dd to your computer and use it in GitHub Desktop.
Drawing realtime graph with SyncGateway and Plot.ly
/*
# ===================
# How to execute
# ===================
# Install dependencies.
$ npm install plotly
$ npm install request
$ npm install moment
# Execute.
$ node sync-streaming.js
*/
var plotly = require('plotly')('your-plotly-account', 'your-api-token');
var request = require('request');
var moment = require('moment');
var graphOptions = {
// fileopt : "extend",
fileopt : "overwrite",
filename : "sync-stream-test",
layout: {
title: "Changes stream",
xaxis: {
type: "date",
autorange: true
},
yaxis: {
type: "linear",
range: [0, 50],
autorange: true
}
}
};
var streamToken = 'jcrlj19ki1';
var init_data = [{
x : [], y : [],
stream : {
token : streamToken,
maxpoints : 20
}
}];
plotly.plot(init_data, graphOptions, function (err, msg) {
if (err) return console.log(err);
console.log(msg);
var stream = plotly.stream(streamToken, function (err, res) {
console.log(err, res);
clearInterval(loop); // once stream is closed, stop writing
});
var since = 0;
var limit = 10;
var fetchFreqInMillis = 1000;
var noDataCnt = 0;
var noDataFreq = 3;
var dateFormat = 'YYYY-MM-DD HH:mm:ss.SSS';
console.log('Start streaming...');
var loop = setInterval(function () {
var option = {
url: 'http://localhost:4984/kitchen-sync/_changes',
json: true,
body: {
include_docs: true,
since: since,
limit: limit
}
};
console.log('Fetching changes...');
request.post(option, function(err, httpResponse, body){
if(err){
return console.error('Failed to fetch changes.', err);
}
var emitted = false;
for(var i = 0; i < body.results.length; i++){
if(typeof(body.results) === 'undefined') continue;
var r = body.results[i];
if((typeof(r.doc) === 'undefined')
|| (r.doc._deleted)
|| (typeof(r.doc.created_at) === 'undefined')) {
continue;
}
console.log(body.results[i]);
var streamObject = {
x: moment(r.doc.created_at).format(dateFormat),
y: r.doc.text.length
};
stream.write(JSON.stringify(streamObject)+'\n');
emitted = true;
}
if(emitted) noDataCnt = 0;
else noDataCnt++;
if(noDataCnt > noDataFreq){
var streamObject = {
x: moment(new Date())
.subtract(fetchFreqInMillis, 'millisecond').format(dateFormat),
y: 0
};
console.log('Writing no data...', streamObject);
stream.write(JSON.stringify(streamObject)+'\n');
noDataCnt = 0;
}
since = body.last_seq;
});
}, fetchFreqInMillis);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment