1- import Firebase from 'firebase'
2- import LRU from 'lru-cache '
1+ // this is aliased in webpack config based on server/client build
2+ import api from 'create-api '
33
4- const inBrowser = typeof window !== 'undefined'
5-
6- // When using bundleRenderer, the server-side application code runs in a new
7- // context for each request. To allow caching across multiple requests, we need
8- // to attach the cache to the process which is shared across all requests.
9- const cache = inBrowser
10- ? null
11- : ( process . __API_CACHE__ || ( process . __API_CACHE__ = createCache ( ) ) )
12-
13- function createCache ( ) {
14- return LRU ( {
15- max : 1000 ,
16- maxAge : 1000 * 60 * 15 // 15 min cache
17- } )
18- }
19-
20- // create a single api instance for all server-side requests
21- const api = inBrowser
22- ? new Firebase ( 'https://hacker-news.firebaseio.com/v0' )
23- : ( process . __API__ || ( process . __API__ = createServerSideAPI ( ) ) )
24-
25- function createServerSideAPI ( ) {
26- const api = new Firebase ( 'https://hacker-news.firebaseio.com/v0' )
27-
28- // cache the latest story ids
29- api . __ids__ = { }
30- ; [ 'top' , 'new' , 'show' , 'ask' , 'job' ] . forEach ( type => {
31- api . child ( `${ type } stories` ) . on ( 'value' , snapshot => {
32- api . __ids__ [ type ] = snapshot . val ( )
33- } )
34- } )
35-
36- // warm the front page cache every 15 min
4+ // warm the front page cache every 15 min
5+ if ( api . cachedIds ) {
376 warmCache ( )
38- function warmCache ( ) {
39- fetchItems ( ( api . __ids__ . top || [ ] ) . slice ( 0 , 30 ) )
40- setTimeout ( warmCache , 1000 * 60 * 15 )
41- }
7+ }
428
43- return api
9+ function warmCache ( ) {
10+ fetchItems ( ( api . cachedIds . top || [ ] ) . slice ( 0 , 30 ) )
11+ setTimeout ( warmCache , 1000 * 60 * 15 )
4412}
4513
4614function fetch ( child ) {
15+ const cache = api . cachedItems
4716 if ( cache && cache . has ( child ) ) {
4817 return Promise . resolve ( cache . get ( child ) )
4918 } else {
@@ -60,8 +29,8 @@ function fetch (child) {
6029}
6130
6231export function fetchIdsByType ( type ) {
63- return api . __ids__ && api . __ids__ [ type ]
64- ? Promise . resolve ( api . __ids__ [ type ] )
32+ return api . cachedIds && api . cachedIds [ type ]
33+ ? Promise . resolve ( api . cachedIds [ type ] )
6534 : fetch ( `${ type } stories` )
6635}
6736
0 commit comments