Permalink
Browse files

Added ability to automatically manage the Posterous API rate-limit of…

… 1 request/sec. Removed superfluous console.log()s
  • Loading branch information...
1 parent b5f7bac commit b6a524bde163b93cccfe747d3845e6f40fd9ed45 @benrhughes committed Feb 19, 2012
Showing with 33 additions and 10 deletions.
  1. +33 −10 lib/posterous.js
View
@@ -5,10 +5,16 @@ var api = require('./api');
var HOST = 'posterous.com';
var PATH = '/api/2/';
+var callExecuting = false;
-var Posterous = function(user, pass, api_token) {
+// Unfortunately Posterous rate-limites API calls to 1/sec. Passing
+// forceSynchronous = true will ensure that the calls comply with this limit.
+// If you do not set forceSynchronous, you will need to manage the rate limit
+// yourself
+var Posterous = function(user, pass, api_token, forceSynchronous) {
this._auth = 'Basic ' + new Buffer(user + ':' + pass).toString('base64');
this._token = api_token;
+ this._synchronous = forceSynchronous;
};
@@ -44,7 +50,6 @@ Posterous.prototype.request = function(method, api, args, callback) {
headers: headers
};
- console.log('uri path: ' + reqOptions.path);
//Make request to Posterous API
var req = http.request(reqOptions, function apiRequest(res) {
//Gather response
@@ -79,8 +84,20 @@ Posterous.prototype.request = function(method, api, args, callback) {
req.end();
};
-Posterous.prototype.makeRequest = function(method, args) {
-console.log('in makeRequest trying');
+Posterous.prototype.makeRequestSync = function(method, args){
+ if(this._synchronous && callExecuting){
+ var that = this;
+ setTimeout(function(){that.makeRequestSync(method, args)}, 1000);
+ }
+ else{
+ callExecuting = true;
+ this.makeRequest(method, args, function(){
+ callExecuting = false;
+ });
+ }
+}
+
+Posterous.prototype.makeRequest = function(method, args, cbk) {
if (args.length < 3) {
return console.error('[Posterous] You must pass arguments to the method.');
}
@@ -121,25 +138,31 @@ console.log('in makeRequest trying');
//console.log(method + ' ' + path);
- this.request(method, path, options, callback);
+ this.request(method, path, options, function(err, result){
+ if(typeof cbk === 'function')
+ cbk();
+
+ callback(err, result);
+ });
+
+
};
Posterous.prototype.get = function() {
- console.log('about to get');
- this.makeRequest('GET', arguments);
+ this.makeRequestSync('GET', arguments);
};
Posterous.prototype.post = function() {
- this.makeRequest('POST', arguments);
+ this.makeRequestSync('POST', arguments);
};
Posterous.prototype.put = function() {
- this.makeRequest('PUT', arguments);
+ this.makeRequestSync('PUT', arguments);
};
Posterous.prototype.del = Posterous.prototype.delete = function() {
- this.makeRequest('DELETE', arguments);
+ this.makeRequestSync('DELETE', arguments);
};
module.exports = Posterous;

0 comments on commit b6a524b

Please sign in to comment.