From b8bc931d5baca0f7ef68cdf76f623972ab0b449d Mon Sep 17 00:00:00 2001 From: Jeff Waugh Date: Tue, 4 Jan 2011 20:36:58 +1100 Subject: [PATCH] Complete 'Friends and Followers resources' section, add _getUsingCursor() utility function --- lib/twitter.js | 78 ++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 76 insertions(+), 2 deletions(-) diff --git a/lib/twitter.js b/lib/twitter.js index a3d85aa9..829fcdbb 100644 --- a/lib/twitter.js +++ b/lib/twitter.js @@ -415,9 +415,15 @@ Twitter.prototype.getWeeklyTrends = function(params, callback) { // List resources Twitter.prototype.getLists = function(screen_name, params, callback) { - // FIXME: handle cursor stuff + if (typeof params === 'function') { + callback = params; + params = null; + } + + params = merge(params, {key:'lists'}); + var url = '/' + screen_name + '/lists.json'; - this.get(url, params, callback); + this._getUsingCursor(url, params, callback); return this; } @@ -531,6 +537,40 @@ Twitter.prototype.deleteDirectMessage // Friends and Followers resources +Twitter.prototype.getFriendsIds = function(id, callback) { + if (typeof id === 'function') { + callback = id; + id = null; + } + + var params = { key: 'ids' }; + if (typeof id === 'string') + params.screen_name = id; + else if (typeof id === 'number') + params.user_id = id; + + var url = '/friends/ids.json'; + this._getUsingCursor(url, params, callback); + return this; +} + +Twitter.prototype.getFollowersIds = function(id, callback) { + if (typeof id === 'function') { + callback = id; + id = null; + } + + var params = { key: 'ids' }; + if (typeof id === 'string') + params.screen_name = id; + else if (typeof id === 'number') + params.user_id = id; + + var url = '/followers/ids.json'; + this._getUsingCursor(url, params, callback); + return this; +} + // Account resources Twitter.prototype.verifyCredentials = function(callback) { @@ -584,3 +624,37 @@ Twitter.prototype.deleteFavorite // Streamed Tweets resources // Search resources + + +/* + * INTERNAL UTILITY FUNCTIONS + */ + +Twitter.prototype._getUsingCursor = function(url, params, callback) { + var self = this, + key = params.key || null, + result = []; + + // if we don't have a key to fetch, we're screwed + if (!key) + callback(new Error('FAIL: Results key must be provided to _getUsingCursor().')); + delete params.key; + + // kick off the first request, using cursor -1 + params = merge(params, {cursor:-1}); + this.get(url, params, fetch); + + function fetch(data) { + // FIXME: what if data[key] is not a list? + if (data[key]) result = result.concat(data[key]); + + if (data.next_cursor_str === '0') { + callback(result); + } else { + params.cursor = data.next_cursor_str; + self.get(url, params, fetch); + } + } + + return this; +}