-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapplication.js
168 lines (147 loc) · 4.68 KB
/
application.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
(function() {
var api = 'http' + (location.hostname === 'localhost' ? '://localhost:3000' : 's://offline-news-api.herokuapp.com') + '/stories';
var synchronizeInProgress;
var db, main;
databaseOpen()
.then(function() {
main = document.querySelector('main');
document.body.addEventListener('click', onClick);
window.addEventListener('popstate', refreshView);
// Only refresh the view if the view is empty
if (main.innerHTML === '') return refreshView();
})
.then(synchronize);
function onClick(e) {
if (e.target.classList.contains('js-link')) {
e.preventDefault();
history.pushState({}, '', e.target.getAttribute('href'));
refreshView();
ga('send', 'pageview', e.target.getAttribute('href'));
}
}
function refreshView() {
var guidMatches = location.pathname.match(/^\/article\/([0-9]+)/);
if (!guidMatches) {
renderAllStories();
return databaseStoriesGet().then(renderAllStories);
}
renderOneStory();
return databaseStoriesGetById(guidMatches[1]).then(renderOneStory);
}
function renderAllStories(stories) {
main.innerHTML = templates.list(stories);
}
function renderOneStory(story) {
if (!story) story = { title: 'Story cannot be found', body: '<p>Please try another</p>' };
main.innerHTML = templates.article(story);
}
function synchronize() {
if (synchronizeInProgress) return synchronizeInProgress;
synchronizeInProgress = Promise.all([serverStoriesGet(), databaseStoriesGet()])
.then(function(results) {
var promises = [];
var remoteStories = results[0];
var localStories = results[1];
// Add new stories downloaded from server to the database
promises = promises.concat(remoteStories.map(function(story) {
if (!arrayContainsStory(localStories, story)) {
return databaseStoriesPut(story);
}
}));
// Delete stories that are no longer on the server from the database
promises = promises.concat(localStories.map(function(story) {
if (!arrayContainsStory(remoteStories, story)) {
return databaseStoriesDelete(story);
}
}));
return promises;
})
// Only refresh the view if it's listing page
.then(function(results) {
if (location.pathname === '/') {
return refreshView();
}
})
.then(function() {
synchronizeInProgress = undefined;
});
}
function arrayContainsStory(array, story) {
return array.some(function(arrayStory) {
return arrayStory.guid === story.guid;
});
}
function databaseOpen() {
return new Promise(function(resolve, reject) {
var version = 1;
var request = indexedDB.open('news-server-rendered', version);
request.onupgradeneeded = function(e) {
db = e.target.result;
e.target.transaction.onerror = reject;
db.createObjectStore('stories', { keyPath: 'guid' });
};
request.onsuccess = function(e) {
db = e.target.result;
resolve();
};
request.onerror = reject;
});
}
function databaseStoriesPut(story) {
return new Promise(function(resolve, reject) {
var transaction = db.transaction(['stories'], 'readwrite');
var store = transaction.objectStore('stories');
var request = store.put(story);
transaction.oncomplete = resolve;
request.onerror = reject;
});
}
function databaseStoriesGet() {
return new Promise(function(resolve, reject) {
var transaction = db.transaction(['stories'], 'readonly');
var store = transaction.objectStore('stories');
var keyRange = IDBKeyRange.lowerBound(0);
// Using reverse direction because the index being sorted on
// ends with a numerical incrementing ID so to get newest news
// first you need to sort by largest first.
var cursorRequest = store.openCursor(keyRange, 'prev');
var data = [];
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if (result) {
data.push(result.value);
result.continue();
} else {
resolve(data);
}
};
});
}
function databaseStoriesGetById(guid) {
return new Promise(function(resolve, reject) {
var transaction = db.transaction(['stories'], 'readonly');
var store = transaction.objectStore('stories');
var request = store.get(guid);
request.onsuccess = function(e) {
var result = e.target.result;
resolve(result);
};
request.onerror = reject;
});
}
function databaseStoriesDelete(story) {
return new Promise(function(resolve, reject) {
var transaction = db.transaction(['stories'], 'readwrite');
var store = transaction.objectStore('stories');
var request = store.delete(story.guid);
transaction.oncomplete = resolve;
request.onerror = reject;
});
}
function serverStoriesGet(guid) {
return fetch(api+'/' + (guid ? guid : ''))
.then(function(res) {
return res.json();
});
}
})();