3
3
/** tweets service, load previous tweets and receives subsequent live tweets for given query */
4
4
angular . module ( 'birdwatch.services' ) . factory ( 'tweets' , function ( $http , utils , $location ) {
5
5
var tweetFeed ;
6
+ var tweetsCache = [ ] ;
6
7
7
8
/** callback function to perform when new tweet(s) arrive */
8
9
var onNewTweets = function ( t ) { } ;
9
10
var registerCallback = function ( callback ) { onNewTweets = callback ; } ;
10
11
11
- /** handle incoming tweets: add to tweets array */
12
- var addTweet = function ( msg ) { onNewTweets ( [ utils . formatTweet ( JSON . parse ( msg . data ) ) ] ) ; } ;
13
-
14
12
/** Load previous Tweets, paginated. Recursive function, calls itself with the next chunk to load until
15
13
* eventually n, the remaining tweets to load, is not larger than 0 any longer. guarantees at least n hits
16
14
* if available, potentially more if (n % chunkSize != 0) */
@@ -20,8 +18,7 @@ angular.module('birdwatch.services').factory('tweets', function ($http, utils, $
20
18
. success ( function ( data ) {
21
19
onNewTweets ( data . hits . hits . reverse ( ) . map ( function ( t ) { return t . _source ; } ) . map ( utils . formatTweet ) ) ;
22
20
loadPrev ( searchString , n - chunkSize , chunkSize , offset + chunkSize ) ;
23
- } ) . error ( function ( data , status , headers , config ) { }
24
- ) ;
21
+ } ) . error ( function ( data , status , headers , config ) { } ) ;
25
22
}
26
23
} ;
27
24
@@ -36,10 +33,19 @@ angular.module('birdwatch.services').factory('tweets', function ($http, utils, $
36
33
}
37
34
else $location . path ( "" ) ;
38
35
36
+ /** handle incoming tweets: add to tweetsCache array, run callback at most every second */
37
+ var cachedCallback = function ( msg ) {
38
+ tweetsCache = tweetsCache . concat ( utils . formatTweet ( JSON . parse ( msg . data ) ) ) ;
39
+ _ . throttle ( function ( ) { // throttle because insertion too expensive on high traffic searches
40
+ onNewTweets ( tweetsCache ) ; // run callback with all items in cache
41
+ tweetsCache = [ ] ; // then empty cache.
42
+ } , 1000 ) ( ) ;
43
+ } ;
44
+
39
45
tweetFeed = new EventSource ( "/tweetFeed?q=" + searchString ) ;
40
- tweetFeed . addEventListener ( "message" , addTweet , false ) ;
46
+ tweetFeed . addEventListener ( "message" , cachedCallback , false ) ;
41
47
42
- loadPrev ( searchString , prevSize , 100 , 0 ) ;
48
+ loadPrev ( searchString , prevSize , 500 , 0 ) ; // load previous tweets in chunks of size 500
43
49
} ;
44
50
45
51
return { search : search , registerCallback : registerCallback } ;
0 commit comments