Skip to content

Commit fbaea43

Browse files
committed
Offline mode: Add REST-based HNService fallback
1 parent 37f709c commit fbaea43

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

src/services/HNServiceRest.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*global fetch*/
2+
require('isomorphic-fetch')
3+
/*
4+
A version of HNService which concumes the Firebase REST
5+
endpoint (https://www.firebase.com/docs/rest/api/). This
6+
is used when a user has enabled 'Offline Mode' in the
7+
Settings panel and ensures responses can be easily fetched
8+
and cached when paired with Service Worker. This cannot be
9+
trivially done using just Web Sockets with the default
10+
Firebase API and provides a sufficient fallback that works.
11+
*/
12+
var endPoint = 'https://hacker-news.firebaseio.com/v0'
13+
var options = {
14+
method: 'GET',
15+
headers: {
16+
'Accept': 'application/json'
17+
}
18+
}
19+
20+
function storiesRef(path) {
21+
return fetch(endPoint + '/' + path + '.json', options)
22+
}
23+
24+
function itemRef(id) {
25+
return fetch(endPoint + '/item/' + id + '.json', options)
26+
}
27+
28+
function userRef(id) {
29+
return fetch(endPoint + '/user/' + id + '.json', options)
30+
}
31+
32+
function updatesRef() {
33+
return fetch(endPoint + '/updates/items/' + '.json', options)
34+
}
35+
36+
function fetchItem(id, cb) {
37+
itemRef(id).once('value', function(snapshot) {
38+
cb(snapshot.val())
39+
})
40+
}
41+
42+
function fetchItems(ids, cb) {
43+
var items = []
44+
ids.forEach(function(id) {
45+
fetchItem(id, addItem)
46+
})
47+
function addItem(item) {
48+
items.push(item)
49+
if (items.length >= ids.length) {
50+
cb(items)
51+
}
52+
}
53+
}
54+
55+
module.exports = {
56+
fetchItem,
57+
fetchItems,
58+
storiesRef,
59+
itemRef,
60+
userRef,
61+
updatesRef
62+
}

0 commit comments

Comments
 (0)