Skip to content

Instantly share code, notes, and snippets.

@Sequoia
Last active October 2, 2015 19:56
Show Gist options
  • Save Sequoia/44336b1d84bfe2b76176 to your computer and use it in GitHub Desktop.
Save Sequoia/44336b1d84bfe2b76176 to your computer and use it in GitHub Desktop.
no idea whether this runs also use babel maybe
PollGh = require('./pollGh');
function handleRes(resBody){
//emit event ??
//write to another process?
//write to disk?
console.log(resBody);
}
function handleErr(err){
console.error(err);
}
poller = PollGh(handleRes,handleErr);
poller.start();
process.on('SIGINT',function(){
poller.stop();
});
"use strict";
var request = require('request-promise')
/**
* @param {Function} callback called with response body each time a response comes from GH
* @param {Function} errhandler called when request errors
* @return {Object}
* {Function} start<-- call to start processing
* {Function} stop <-- call to stop processing
*/
module.exports = function PollGh(callback,errhandler){
var running = null; //will hold intervalobject
var waiting = null; //will hold reset timeout
var delay = null; //how long to wait to restart
var options = {
url : 'https://api.github.com/events',
headers : {
"User-Agent": "codejudge-events"
},
resolveWithFullResponse : true
};
function disableOnRateLimit(res){ //simplify (for now)
if (parseInt(res.headers['x-ratelimit-remaining'], 10) === 0) {
clearInterval(running);
running = null;
resetTime = parseInt(res.headers['x-ratelimit-reset'], 10);
delay = resetTime - (Date.now() / 1000);
waiting = setTimeout(go,delay + 3000); //+3 seconds just to be safe ;)
}
return res;
}
function pollServer() {
request(options)
.then(disableOnRateLimit)
.then(res => res.body)
.then(callback)
.catch(errhandler);
if (Date.now() / 1000 > resetTime) active = true;
}
function go(){
running = setInterval(pollServer, 5000);
}
function stop(){
clearInterval(running);
running = null;
clearTimeout(waiting);
waiting = null;
}
return {
start : go,
stop : stop
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment