-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
index.js
76 lines (66 loc) · 1.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// this is aliased in webpack config based on server/client build
import { createAPI } from 'create-api'
const logRequests = !!process.env.DEBUG_API
const api = createAPI({
version: '/v0',
config: {
databaseURL: 'https://hacker-news.firebaseio.com'
}
})
// warm the front page cache every 15 min
// make sure to do this only once across all requests
if (api.onServer) {
warmCache()
}
function warmCache () {
fetchItems((api.cachedIds.top || []).slice(0, 30))
setTimeout(warmCache, 1000 * 60 * 15)
}
function fetch (child) {
logRequests && console.log(`fetching ${child}...`)
const cache = api.cachedItems
if (cache && cache.has(child)) {
logRequests && console.log(`cache hit for ${child}.`)
return Promise.resolve(cache.get(child))
} else {
return new Promise((resolve, reject) => {
api.child(child).once('value', snapshot => {
const val = snapshot.val()
// mark the timestamp when this item is cached
if (val) val.__lastUpdated = Date.now()
cache && cache.set(child, val)
logRequests && console.log(`fetched ${child}.`)
resolve(val)
}, reject)
})
}
}
export function fetchIdsByType (type) {
return api.cachedIds && api.cachedIds[type]
? Promise.resolve(api.cachedIds[type])
: fetch(`${type}stories`)
}
export function fetchItem (id) {
return fetch(`item/${id}`)
}
export function fetchItems (ids) {
return Promise.all(ids.map(id => fetchItem(id)))
}
export function fetchUser (id) {
return fetch(`user/${id}`)
}
export function watchList (type, cb) {
let first = true
const ref = api.child(`${type}stories`)
const handler = snapshot => {
if (first) {
first = false
} else {
cb(snapshot.val())
}
}
ref.on('value', handler)
return () => {
ref.off('value', handler)
}
}