-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserDataLoader.js
More file actions
332 lines (332 loc) · 11.8 KB
/
UserDataLoader.js
File metadata and controls
332 lines (332 loc) · 11.8 KB
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
window.JSON = window.JSON || require('json3');
/**
* A User Data Loader API that can load user data from any provider using the {@link UserDataProvider.js}
* API to expose user data.
*
* This function has a prototype that exposes two methods for loading user data:
* <li>loadUserData(request) - get user data from a single provider</li>
* <li>loadAllUserData(request) - get user data from a collection of providers in parallel</li>
*
* Example usage:
* <pre><code>
* var udl =new UserDataLoader().loadUserData({
* url: 'http://bidder.com/csud/userDataProvider.html',
* timeout: 75,
* responseHandler: function(error, result){
* if(error){
* throw new Error('Could not get user data from bidder:' + error);
* }
* var bidderUserId = result.id;
* ...
* }
* });
* </code></pre>
*
* <pre><code>
* var udl = new UserDataLoader().loadAllUserData({
* timeout: 100,
* partners: {
* 'dbm': { url: '//dbm.com/csud/userDataProvider.html' },
* 'iponweb': { url: '//bidswitch.com/csud/udp.html'}
* },
* responseHandler: function(error, results){
* if(error){
* throw new Error('Could not get user data from any partners:' + error);
* }
* if(!results['dbm'].error){
* var dbmUserData = results['dbm'].result,
* dbmUserId = dbmUserData.id;
* ...
* }
* ...
* }
* });
* </code></pre>
*
* @constructor
*/
var UserDataLoader = function UserDataLoader(){
/* initialize a collection of iframes used for user data requests at any moment in time */
this.iframes = {};
/* initialize any relevant listensers */
this.init();
};
/**
* A global counter used for generating message identifiers
*/
UserDataLoader.counter = 0;
UserDataLoader.prototype = {
/**
* Handle a user data response payload by
* <li>invoking the requested response handler</li>
* <li>clearing any set timeouts for request</li>
* <li>removing iframe related to request from iframes object</li>
* <li>removing iframe related to request from the DOM</li>
*
* @param {Object} payload object - must contain an "id" property and either a "result" or "error"
*/
handleResponse: function handleResponse(payload){
if(payload && payload.id){
var iframe = this.iframes[payload.id];
if(iframe){
try{
iframe.handleResponse(payload.error,payload.result);
}catch(clientHandlerExecutionError){
/*ignore*/
}
try{
clearTimeout(iframe.timeoutFn);
}catch(timeoutClearError){
/* ignore */
}
delete this.iframes[payload.id];
this.removeDomElement(iframe);
}
}
},
/**
* Initialize any relevant event listeners
*/
init: function init(){
var me = this;
if(me.hasPostMessage()){
me.windowEventListener = function(event) {
try{
me.handleResponse(JSON.parse(event.data));
}catch(handlerError){
/*ignore*/
}
};
if(window.addEventListener){
window.addEventListener('message', me.windowEventListener);
}else{
window.attachEvent('onmessage', me.windowEventListener);
}
}
},
/**
* Check whether browser has window.postMessage support
* @returns {Boolean} true if browser has window.postMessage support
*/
hasPostMessage: function hasPostMessage(){
return window.postMessage ? true: false;
},
/**
* Load user data from a single csud partner. Expects a request object that contains the following
* properties:
* <li>url {string}
* - mandatory URL of html page running {@link UserDataProvider.js}</li>
* <li>responseHandler {function}
* - mandatory node-compatible response handler function (function(error,result)); results
* are Objects containing a mandatory "id":{string} property</li>
* <li>timeout {number}
* - optional timeout in milliseconds; timeouts will result in 'timeout' errors</li>
* <li>payload {object}
* - optional payload to send along with a user data request</li>
*
* Example usage:
* <pre><code>
* var udl = new UserDataLoader().loadUserData({
* url: 'http://bidder.com/csud/userDataProvider.html',
* timeout: 75,
* responseHandler: function(error, result){
* if(error){
* throw new Error('Could not get user data from bidder:' + error);
* }
* var bidderUserId = result.id;
* ...
* }
* });
* </code></pre>
*
* Example responseHandler result:
* <pre><code>
* {
* id: 'mandatory-user-id',
* ext: {
* opt: 'optional extra data'
* }
* }
* </code></pre>
*
* @param {object} request - a request containing url,responseHandler,timeout, and payload properties
* @return {function} this
*/
loadUserData: function loadUserData(request){
var me = this,
id = ++UserDataLoader.counter,
message = escape(JSON.stringify({
id: id,
payload: request.payload
})),
iframe = document.createElement('iframe');
iframe.style.width = '0px';
iframe.style.height = '0px';
iframe.style.display = 'none';
iframe.handleResponse = request.responseHandler;
this.iframes[id] = iframe;
if(request.timeout){
iframe.timeoutFn = setTimeout(function(){
me.handleResponse({error:'timeout',id:id});
},request.timeout);
}
iframe.src = request.url + '#' + message;
if(!this.hasPostMessage()){
var onload = function () {
try{
if(iframe.contentWindow.name){
me.handleResponse(JSON.parse(iframe.contentWindow.name));
}
}catch(couldNotAccessWindowName){
/* ignore */
iframe.onload = onload;
}
};
var onerror = function () {
/* ignore */
/* TODO: consider failfast */
};
iframe.onload = onload;
iframe.onerror = onerror;
if(iframe.attachEvent){
iframe.attachEvent('onload',onload);
iframe.attachEvent('onerror',onerror);
}
}
document.body.appendChild(iframe);
return this;
},
/**
* Load user data from a multiple csud partners. Expects a request object that contains the following
* properties:
* <li>timeout {number}
* - mandatory timeout in milliseconds; timeouts will result in 'timeout' errors</li>
* <li>partners {object}
* - mandatory object containing partner objects with url {string}, optional timeout {number},
* optional payload {object} properties (e.g. {url:'http://...',timeout:130,payload:{}})
* timeouts specified by-partner take priority over global timeout for all requests.
* <li>responseHandler {function}
* - mandatory node-compatible response handler function (function(error,result)); results
* is an object with a 'partnerResponses' property which is an object with keys representing partner
* names from the partners object and values containing either "result" Object properties
* or "error" strings</li>
*
* Example usage:
* <pre><code>
* var udl = new UserDataLoader().loadAllUserData({
* timeout: 100,
* partners: {
* 'dbm': { url: '//dbm.com/csud/userDataProvider.html' },
* 'iponweb': { url: '//bidswitch.com/csud/udp.html'}
* },
* responseHandler: function(error, results){
* if(error){
* throw new Error('Could not get user data from any partners:' + error);
* }
* var totalResponseTime = results.rtime,
* partnerResponses = results.partnerResponses;
*
* if(!partnerResponses['dbm'].error){
* var dbmUserData = partnerResponses['dbm'].result,
* dbmUserId = dbmUserData.id;
* ...
* }
* ...
* }
* });
* </code></pre>
*
* Example responseHandler results:
* <pre><code>
* {
* partnerResponses: {
* 'test-dsp': {
* result: {
* id: 'test-dsp-user-id',
* ext: {}
* },
* rtime: 14
* },
* 'another-partner': {
* error: 'timeout',
* rtime: 25
* }
* },
* rtime: 26
* }
* </code></pre>
*
* @param {object} request - a request containing timeout,responseHandler, and partner properties
* @return {function} this
*/
loadAllUserData: function loadAllUserData(request){
var results = {},
requestStartMs = new Date().getTime(),
outstandingRequests = 1,
completionHandler = function(){
if(--outstandingRequests === 0){
/* all requests completed */
request.responseHandler(undefined,{
rtime: new Date().getTime() - requestStartMs,
partnerResponses: results
});
}
},
createHandler = function(partnerId){
return function(error,result){
var partnerResult = {};
if(error){
partnerResult.error = error;
}
if(result){
partnerResult.result = result;
}
partnerResult.rtime = new Date().getTime() - requestStartMs;
results[partnerId] = partnerResult;
completionHandler();
};
};
for(var partnerId in request.partners){
var partnerConfig = request.partners[partnerId];
outstandingRequests++;
this.loadUserData({
url: partnerConfig.url,
timeout: partnerConfig.timeout || request.timeout,
payload: partnerConfig.payload,
responseHandler: createHandler(partnerId)
});
}
completionHandler();
},
/**
* Close this UserDataLoader, cleaning up any iframes and event listeners created during
* the UseerDataLoader's lifetime
*/
close: function close(){
if(this.windowEventListener){
if(window.removeEventListener){
window.removeEventListener('message', this.windowEventListener);
}else{
window.detachEvent('message', this.windowEventListener);
}
}
for(var id in this.iframes){
var iframe = this.iframes[id];
delete this.iframes[id];
this.removeDomElement(iframe);
}
},
/**
* Remove a DOM element from the document
*/
removeDomElement: function removeDomElement(domElement){
try{
if(domElement && domElement.parentNode){
domElement.parentNode.removeChild(domElement);
}
}catch(domRemovalError){
/* ignore */
}
}
};
module.exports = UserDataLoader;