-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstory-viewer-promises.js
168 lines (146 loc) · 4.5 KB
/
story-viewer-promises.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
/**
* An app that should display a story title and chapters.
*
* Request the story from the server using a GET 'story' request.
*
* The response will be a status 200 with a JSON string representation of the following object:
* <pre>
* {
* title: 'My Story',
* chapters: ['chapter1', 'chapter2', 'chapter3', 'chapter4']
* serial: true
* }
* </pre>
*
* If the <code>serial</code> flag is set, chapters should be requested one after the other i.e. no overlapping requests.
* If the <code>serial</code> flag is not set, chapters can be requested in parallel.
*
* Request each chapter from the server using a GET 'chapter?id=' request.
*
* The response will be a status 200 with a JSON string representation of the following object:
* <pre>
* {
* id: 'chapter1',
* text: 'Lorem ipsum'
* }
* </pre>
*
* Responses may fail with status 404 if the story, or chapter, is not found.
*/
class StoryViewer {
//#region Pre-defined API
/**
* Show or hide the loading animation.
* @param {Boolean} bool Show the loader if true; hide the loader if false.
*/
setLoaderVisible(bool) {
var loader = document.getElementById('loader');
loader.style.visibility = (bool ? 'visible' : 'hidden');
}
/**
* Set the story title text.
* @param {String} text Title text.
*/
setStoryTitle(title) {
var titleElement = document.getElementById('title');
titleElement.innerText = title;
}
/**
* Display a new chapter in the DOM.
* @param {String} id ID of the chapter to insert (provided by server in initial story definition).
* @param {String} text Text content of the chapter.
*/
insertChapter(id, text) {
var div = document.createElement('div');
div.classList.add('chapter');
div.innerText = `[${id}] ${text}`;
document.body.appendChild(div);
}
/**
* Report an error e.g. if story or chapter loading fails.
* @param {String} status Status of the error.
*/
reportError(status) {
console.error(status);
}
/**
* Reset the DOM, and internal state variables.
* Called after each test.
*/
reset() {
this.story = null;
this.chapters = null;
this.setLoaderVisible(false);
this.setStoryTitle('');
var chapters = document.querySelectorAll('.chapter');
for (let i = 0; i < chapters.length; ++i) {
let chapter = chapters[i];
chapter.parentNode.removeChild(chapter);
}
}
//#endregion
request(url) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest()
xhr.open('get', url);
xhr.addEventListener('readystatechange', () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
resolve(xhr.responseText);
} else if (xhr.status === 404) {
reject(xhr.statusText);
}
}
});
xhr.send();
});
}
constructor() {
//this.story = null;
//this.chapters = null;
this.requestStory();
}
requestStory() {
var storyPromise = this.request('story').then(storyData => {
var story = JSON.parse(storyData);
this.setStoryTitle(story.title);
// Ensure any errors thrown by chapter requests are caught below.
return this.requestChapters(story);
}).catch(this.reportError);
var minLoaderDelayPromise = new Promise((resolve, reject) => {
setTimeout(resolve, StoryViewer.MIN_LOADER_TIME);
});
this.setLoaderVisible(true);
Promise.all([storyPromise, minLoaderDelayPromise]).then(() => {
this.setLoaderVisible(false);
});
}
requestChapters(story) {
if (story.serial) {
// Return final Promise chain from reduce(), so that any errors are handled at the top level.
return story.chapters.reduce((promiseChain, chapterId) => {
// Enqueue each chapter request.
return promiseChain.then(() => {
// If request is rejected, remained of chain will be skipped; execution will jump to top-level catch().
return this.request(`chapter?id=${chapterId}`).then(chapterData => {
// Insert received chapter: safe to do in serial order.
var chapter = JSON.parse(chapterData);
this.insertChapter(chapter.id, chapter.text);
});
});
}, Promise.resolve()); // Initialise chain with Resolved Promise at head.
} else {
// Create an array of chapter requests, and pass to Promise.all().
return Promise.all(story.chapters.map(chapterId => {
return this.request(`chapter?id=${chapterId}`).then(chapterData => {
var chapter = JSON.parse(chapterData);
this.insertChapter(chapter.id, chapter.text);
});
}));
}
}
}
/**
* Minimum number of milliseconds the loader should be shown for.
*/
StoryViewer.MIN_LOADER_TIME = 1000;