Last active
December 7, 2015 22:32
-
-
Save WickedDevice/2ec58eb22eec4423c858 to your computer and use it in GitHub Desktop.
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
var Promise = require("bluebird"); | |
var bhttp = Promise.promisifyAll(require("bhttp")); | |
// config encapsulates opensensors-api-key | |
module.exports = function(config) { | |
var API_POST_OPTIONS = { | |
headers: { | |
Accept: "application/json", | |
Authorization: "api-key " + config["api-key"] | |
} | |
}; | |
var API_BASE_URL = "https://api.opensensors.io/v1/"; | |
// returns an array of message payloads from the API, augmented with timestamp | |
function collectMessagesByDevice(client_id, params){ | |
var url = API_BASE_URL + "messages/device"; | |
if(!client_id){ | |
console.error("client-id is required"); | |
return Promise.resolve({}); | |
} | |
url += "/" + client_id; | |
var first = true; | |
var results = []; | |
var previousResultHasNext = null; | |
promiseWhile( | |
function(){ //predicate | |
var ret = false; | |
if(first || previousResultHasNext){ | |
ret = true; | |
} | |
first = false; | |
return ret; | |
}, | |
function(){ // action | |
previousResultHasNext = false; | |
if(!params){ | |
params = {}; | |
} | |
return bhttp.post(url, params, API_POST_OPTIONS).then(function(response){ | |
results.push(response); | |
previousResultHasNext = response.next; | |
}); | |
} | |
).then(function(){ | |
console.log("Done"); | |
}); | |
} | |
return { | |
messages: { | |
byDevice: collectMessagesByDevice, | |
byTopic: function(topic, params){ | |
}, | |
byUser: function(user_id, params){ | |
} | |
} | |
}; | |
}; | |
var promiseWhile = function(condition, action) { | |
var resolver = Promise.defer(); | |
var loop = function() { | |
if (!condition()) return resolver.resolve(); | |
return Promise.cast(action()) | |
.then(loop) | |
.catch(resolver.reject); | |
}; | |
process.nextTick(loop); | |
return resolver.promise; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment