forked from Detachment/Build-vue-hackernews-2.0-from-scratch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.js
67 lines (57 loc) · 1.48 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
var config = {
databaseURL: "https://hacker-news.firebaseio.com"
};
firebase.initializeApp(config);
var api = firebase.database().ref('/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()
})
});
// console.log(api);
// warm the front page cache every 15 mins
warmCache();
function warmCache() {
fetchItems((api.__ids__.top || [] ).slice(0, 30));
setTimeout(warmCache, 1000*15*60);
};
// use Promise here to ensure have got datas before rendering
function fetch(child) {
return new Promise((resolve, reject) => {
api.child(child).once('value', snapshot => {
const val = snapshot.val();
resolve(val);
}, reject)
})
};
function fetchIdsByType(type) {
return api.__ids__[type]
? Promise.resolve(api.__ids__[type])
: fetch(`${type}stories`)
};
function fetchItem(id) {
return fetch(`item/${id}`)
};
function fetchItems(ids) {
return Promise.all(ids.map(id => fetchItem(id)))
};
function fetchUser(id) {
return fetch(`user/${id}`)
};
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)
}
}