@@ -118,6 +118,25 @@ OAuthParams.prototype.getHeader = function(){
118118 */
119119function TwitterClient ( ) {
120120 this . deAuth ( ) ;
121+ // register rate limits for all REST calls
122+ this . lastCall = null ;
123+ this . lastMeta = { } ;
124+ }
125+
126+ TwitterClient . prototype . getLastMeta = function ( method ) {
127+ return this . lastMeta [ method || this . lastCall ] || { limit : 0 , remaining : 0 , reset : 0 } ;
128+ }
129+
130+ TwitterClient . prototype . getRateLimit = function ( method ) {
131+ return this . getLastMeta ( method ) . limit ;
132+ }
133+
134+ TwitterClient . prototype . getRateLimitRemaining = function ( method ) {
135+ return this . getLastMeta ( method ) . remaining ;
136+ }
137+
138+ TwitterClient . prototype . getRateLimitReset = function ( method ) {
139+ return new Date ( this . getLastMeta ( method ) . reset * 1000 ) ;
121140}
122141
123142TwitterClient . prototype . setAuth = function ( consumerKey , consumerSecret , accessKey , accessSecret ) {
@@ -159,6 +178,8 @@ TwitterClient.prototype._rest = function( requestMethod, requestPath, requestArg
159178 console . error ( 'No callback for ' + requestMethod + ' ' + requestUri ) ;
160179 }
161180 }
181+ this . lastCall = requestPath ;
182+ var client = this ;
162183 return this . call ( requestMethod , requestUri , requestArgs , TWITTER_API_TIMEOUT , function ( res , err ) {
163184 if ( ! res ) {
164185 callback ( null , err , 0 ) ;
@@ -191,6 +212,16 @@ TwitterClient.prototype._rest = function( requestMethod, requestPath, requestArg
191212 callback ( data , error , res . statusCode ) ;
192213 }
193214 } ) ;
215+ // remember last rest call
216+ // pull rate limit data from headers
217+ var limit = res . headers [ 'x-rate-limit-limit' ] ;
218+ if ( limit ) {
219+ client . lastMeta [ client . lastCall ] = {
220+ limit : Number ( limit ) ,
221+ remaining : Number ( res . headers [ 'x-rate-limit-remaining' ] ) ,
222+ reset : Number ( res . headers [ 'x-rate-limit-reset' ] )
223+ }
224+ }
194225 } ) ;
195226}
196227
0 commit comments