forked from vuejs/vue-hackernews-2.0
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi.js
92 lines (79 loc) · 2.34 KB
/
api.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const Firebase = require('firebase')
const LRU = process.BROWSER ? null : require('lru-cache')
// When using bundleRenderer, the server-side application code runs in a new
// context for each request. To allow caching across multiple requests, we need
// to attach the cache to the process which is shared across all requests.
const cache = process.BROWSER
? null
: (process.__API_CACHE__ || (process.__API_CACHE__ = createCache()))
function createCache () {
return LRU({
max: 1000,
maxAge: 1000 * 60 * 15 // 15 min cache
})
}
// create a single api instance for all server-side requests
const api = process.BROWSER
? new Firebase('https://hacker-news.firebaseio.com/v0')
: (process.__API__ || (process.__API__ = createServerSideAPI()))
function createServerSideAPI () {
const api = new Firebase('https://hacker-news.firebaseio.com/v0')
// cache the latest story ids
api.__ids__ = {}
;['top', 'new', 'show', 'ask', 'job'].forEach(type => {
api.child(`${type}stories`).on('value', snapshot => {
api.__ids__[type] = snapshot.val()
})
})
// warm the front page cache every 15 min
warmCache()
function warmCache () {
fetchItems((api.__ids__.top || []).slice(0, 30))
setTimeout(warmCache, 1000 * 60 * 15)
}
return api
}
function fetch (child) {
if (cache && cache.has(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)
resolve(val)
}, reject)
})
}
}
export function fetchIdsByType (type) {
return api.__ids__ && api.__ids__[type]
? Promise.resolve(api.__ids__[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)
}
}