This repository has been archived by the owner on Dec 5, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
async-fragment-tag.js
232 lines (190 loc) · 7.15 KB
/
async-fragment-tag.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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
'use strict';
var logger = require('raptor-logging').logger(module);
var asyncWriter = require('async-writer');
var AsyncValue = require('raptor-async/AsyncValue');
var isClientReorderSupported = require('./client-reorder').isSupported;
function isPromise(o) {
return o && typeof o.then === 'function';
}
function promiseToCallback(promise, callback, thisObj) {
if (callback) {
var finalPromise = promise
.then(function(data) {
callback(null, data);
});
if (typeof promise.catch === 'function') {
finalPromise = finalPromise.catch(function(err) {
callback(err);
});
} else if (typeof promise.fail === 'function') {
finalPromise = finalPromise.fail(function(err) {
callback(err);
});
}
if (finalPromise.done) {
finalPromise.done();
}
}
return promise;
}
function requestData(provider, args, callback, thisObj) {
if (isPromise(provider)) {
// promises don't support a scope so we can ignore thisObj
promiseToCallback(provider, callback);
return;
}
if (typeof provider === 'function') {
var data = (provider.length === 1) ?
// one argument so only provide callback to function call
provider.call(thisObj, callback) :
// two arguments so provide args and callback to function call
provider.call(thisObj, args, callback);
if (data !== undefined) {
if (isPromise(data)) {
promiseToCallback(data, callback);
}
else {
callback(null, data);
}
}
} else {
// Assume the provider is a data object...
callback(null, provider);
}
}
module.exports = function render(input, out) {
var dataProvider = input.dataProvider;
var arg = input.arg || {};
arg.out = out;
var clientReorder = isClientReorderSupported && input.clientReorder === true;
var asyncOut;
var done = false;
var timeoutId = null;
var name = input.name || input._name;
var scope = input.scope || this;
var method = input.method;
if (method) {
dataProvider = dataProvider[method].bind(dataProvider);
}
var fragmentInfo = {
name: name,
clientReorder: clientReorder,
dataProvider: dataProvider
};
var beforeRenderEmitted = false;
out.emit('asyncFragmentBegin', fragmentInfo);
function renderBody(err, data, timeoutMessage) {
if (fragmentInfo.finished) {
return;
}
if (timeoutId) {
clearTimeout(timeoutId);
timeoutId = null;
}
done = true;
var targetOut = fragmentInfo.out = asyncOut || out;
if (!beforeRenderEmitted) {
beforeRenderEmitted = true;
out.emit('asyncFragmentBeforeRender', fragmentInfo);
}
if (err) {
if (input.errorMessage) {
console.error('Async fragment (' + name + ') failed. Error:', (err.stack || err));
targetOut.write(input.errorMessage);
} else {
targetOut.error(err);
}
} else if (timeoutMessage) {
asyncOut.write(timeoutMessage);
} else {
if (input.renderBody) {
input.renderBody(targetOut, data);
}
}
fragmentInfo.finished = true;
if (!clientReorder) {
out.emit('asyncFragmentFinish', fragmentInfo);
}
if (asyncOut) {
asyncOut.end();
// Only flush if we rendered asynchronously and we aren't using
// client-reordering
if (!clientReorder) {
out.flush();
}
}
}
requestData(dataProvider, arg, renderBody, scope);
if (!fragmentInfo.finished) {
var timeout = input.timeout;
var timeoutMessage = input.timeoutMessage;
if (timeout == null) {
timeout = 10000;
} else if (timeout <= 0) {
timeout = null;
}
if (timeout != null) {
timeoutId = setTimeout(function() {
var message = 'Async fragment (' + name + ') timed out after ' + timeout + 'ms';
fragmentInfo.timedout = true;
if (timeoutMessage) {
logger.error(message);
renderBody(null, null, timeoutMessage);
} else {
renderBody(new Error(message));
}
}, timeout);
}
if (clientReorder) {
var asyncFragmentContext = out.global.__asyncFragments || (asyncFragmentContext = out.global.__asyncFragments = {
fragments: [],
nextId: 0
});
var id = fragmentInfo.id = input.name || (asyncFragmentContext.nextId++);
if (input.placeholder) {
out.write('<span id="afph' + id + '">' + (input.placeholder || '') + '</span>');
} else {
out.write('<noscript id="afph' + id + '"></noscript>');
}
var asyncValue = fragmentInfo.asyncValue = new AsyncValue();
// If `client-reorder` is enabled then we asynchronously render the async fragment to a new
// AsyncWriter instance so that we can Write to a temporary in-memory buffer.
asyncOut = fragmentInfo.out = asyncWriter.create(null, {global: out.global});
fragmentInfo.after = input.showAfter;
var oldEmit = asyncOut.emit;
// Since we are rendering the async fragment to a new and separate AsyncWriter instance,
// we want to proxy any child events to the main AsyncWriter in case anyone is interested
// in those events. This is also needed for the following events to be handled correctly:
//
// - asyncFragmentBegin
// - asyncFragmentBeforeRender
// - asyncFragmentFinish
//
asyncOut.emit = function(event) {
if (event !== 'finish' && event !== 'error') {
// We don't want to proxy the finish and error events since those are
// very specific to the AsyncWriter associated with the async fragment
out.emit.apply(out, arguments);
}
oldEmit.apply(asyncOut, arguments);
};
asyncOut
.on('finish', function() {
asyncValue.resolve(asyncOut.getOutput());
})
.on('error', function(err) {
asyncValue.reject(err);
});
if (asyncFragmentContext.fragments) {
asyncFragmentContext.fragments.push(fragmentInfo);
}
out.emit('asyncFragmentClientReorder', fragmentInfo);
} else {
out.flush(); // Flush everything up to this async fragment
asyncOut = fragmentInfo.out = out.beginAsync({
timeout: 0, // We will use our code for controlling timeout
name: name
});
}
}
};