Skip to content

Commit

Permalink
error handling. pages.
Browse files Browse the repository at this point in the history
  • Loading branch information
chjj committed Nov 21, 2012
1 parent 1cba772 commit 04b07fe
Showing 1 changed file with 35 additions and 41 deletions.
76 changes: 35 additions & 41 deletions lib/charged.js
Expand Up @@ -880,14 +880,15 @@ Charged.prototype.request = function(options, callback) {
return callback(new Error('Not found.'));
}

if (res.statusCode >= 400) {
return callback(new Error('Status code: ' + res.statusCode));
}

try {
if (typeof body === 'string') {
body = JSON.parse(body);
}
} catch (e) {
// For debugging:
// e.message += '\nJSON: "' + body + '"';
// return callback(e);
return callback(new Error(
'The JSON returned from chargify'
+ ' is failing to parse.'
Expand All @@ -902,7 +903,7 @@ Charged.prototype.request = function(options, callback) {
});
};

Charged.prototype.get = function(path, query, callback, format, ignore) {
Charged.prototype.get = function(path, query, callback, format) {
var self = this;

if (typeof query === 'function') {
Expand All @@ -911,44 +912,37 @@ Charged.prototype.get = function(path, query, callback, format, ignore) {
query = null;
}

if (query && query.per_page > 50 && query.page == null) {
var max = query.per_page
, out = [];

query.per_page = 200;
query.page = 0;

(function next() {
query.page++;
return self.get(path, query, function(err, results) {
if (err) return callback(err);

if (!results.length) {
return callback(null, out);
}

out.push.apply(out, results);

if (out.length >= max) {
out = out.slice(0, max);
return callback(null, out);
}

return next();
}, format);
})();

return;
}

if (query) {
// Caps:
// subscriptions, component usages: 200
// customers: 50
// NOTE:
// If we just used 200, or 50, for both
// per_page assignment and comparison
// below, we wouldn't need this 'ignore'
// varable.
if (!ignore && query.per_page > 50) {
var max = query.per_page
, out = [];

query.per_page = 200;
query.page = 0;

(function next() {
query.page++;
return self.get(path, query, function(err, results) {
if (err) return callback(err);

if (!results.length) {
return callback(null, out);
}

out.push.apply(out, results);

if (out.length >= max) {
out = out.slice(0, max);
return callback(null, out);
}

return next();
}, format, true);
})();

return;
}
query = qs.stringify(query);
path += ~path.indexOf('?')
? '&' + query
Expand Down

0 comments on commit 04b07fe

Please sign in to comment.