-
Notifications
You must be signed in to change notification settings - Fork 3
/
api-client.js
495 lines (424 loc) · 17.1 KB
/
api-client.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
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
// This file may run in a browser, so wrap it in an IIFE.
(function() {
'use strict';
var context = typeof exports !== 'undefined' ? exports : window;
var base64 = context.btoa || require('btoa');
var Promise = context.Promise;
if (!Promise && typeof(require) === 'function') {
Promise = require('bluebird');
}
var COOKIE_KEYVALUE_SEPARATOR = /; */;
// ## TaggedApi Constructor
//
// Creates a new Tagged API client that is bound to the request's cookies.
// Each full page request by the user should create a new instance of the API
// client to ensure that the calls are made on behalf of the user.
//
// **Params:**
//
// endpoint: [string] URL to post API calls to.
// options: [object|null] Common options that are used with each API call.
// http: [HttpAdapter|null] Adapter to make HTTP requests.
var TaggedApi = function(endpoint, options, http) {
this._endpoint = endpoint;
// Default to the vanilla adapter should clients not pass adapter
this._http = (typeof http !== 'undefined') ? http : new VanillaAdapter(context.XMLHttpRequest, context.Promise || require('bluebird'));
// API calls that are made within a single JS execution frame will be added
// to the queue and processed as a whole on the next tick.
this._queue = [];
// When the queue size exceeds this value, an HTTP request will be trigged
// to flush the queue. Defaults to `null`, meaning no limit.
this._maxQueueSize = null;
// This timeout is used to trigger the HTTP request on the next tick. All
// API calls that are added to the queue will be batched together.
this._batchTimeout = null;
// Common parameters that will be passed with each API call are stored here.
this._options = mergeRecursive({
// These parameters are appended to the endpoint as a query string.
query: {},
// Parameters registered here will be merged with parameters that are
// passed in to the `execute()` call.
params: {
// Track is autogenerated per API instance, allowing the API server
// to know which API calls are made within a single requst.
track: this._generateTrackId()
},
// How long to wait before aborting long-running requests.
timeout: 10000
}, options || {});
// The user's cookies are required by the API to properly handle the request.
// Keep a reference so that we can ensure we use updated cookies.
this._cookies = {};
if (options.cookies) {
var cookies = options.cookies.split(COOKIE_KEYVALUE_SEPARATOR);
cookies.forEach(function(cookie) {
var keyValuePair = cookie.split('=', 2);
this._cookies[keyValuePair[0]] = keyValuePair[1];
}.bind(this));
}
var timeout = parseInt(this._options.timeout, 10) || 10000;
if (timeout < 0) timeout = 10000;
this._http.setTimeout(timeout);
this._events = {};
this._cache = {};
};
// Generates a random track ID.
TaggedApi.prototype._generateTrackId = function() {
return base64(Math.random() * (100000000)).substr(0, 10);
};
// Sets the max queue size.
TaggedApi.prototype.setMaxQueueSize = function(maxQueueSize) {
this._maxQueueSize = maxQueueSize;
};
// Returns the max queue size, or null if unlimited.
TaggedApi.prototype.getMaxQueueSize = function(maxQueueSize) {
return this._maxQueueSize;
};
// Executes an API call with given method and params. Returns a promise that
// is resolved with the API call's response data, or rejected if the API response
// cannot be parsed as JSON. Additionally, if the result contains a `stat` property
// that does not equal `ok`, then the promise will be rejected.
TaggedApi.prototype.execute = function(method, params, config) {
if (!method || typeof method !== "string") {
throw new Error("Method is required to execute API calls");
}
// check if we should clear old caches
var randomNum = Math.random();
if (randomNum > 0.99) {
var now = new Date().getTime();
for (var cacheEntry in this._cache) {
if (this._cache[cacheEntry].expires < now) {
delete this._cache[cacheEntry];
}
}
}
var cacheKey;
// check if config.cache is passed in
if (config && config.cache) {
// create a cache key based on method and params
cacheKey = method + ':' + JSON.stringify(params);
// check cache for existing promise
if (this._cache.hasOwnProperty(cacheKey)) {
var cache = this._cache[cacheKey];
var now = new Date().getTime();
// see if cache is expired - delete if it is
if (cache.expires > now) {
return this._cache[cacheKey];
} else {
delete this._cache[cacheKey];
}
}
}
var promise = new Promise(function(resolve, reject) {
var _params = mergeRecursive({}, this._options.params);
this._queue.push({
method: method,
params: mergeRecursive(_params, params || {}),
deferred: {resolve: resolve, reject: reject},
timeStart: getHighResolutionTimeStamp()
});
if (this._maxQueueSize && this._queue.length >= this._maxQueueSize) {
// Flush the queue
this._postToApi();
} else if (null === this._batchTimeout) {
this._batchTimeout = setTimeout(this._postToApi.bind(this), 1);
}
}.bind(this));
if (cacheKey) {
var now = new Date().getTime();
var expires = (config.cache === true) ? Infinity : (now + (config.cache * 1000));
this._cache[cacheKey] = {
expires: expires,
promise: promise
};
}
return promise;
};
TaggedApi.prototype._postToApi = function() {
var body = stringifyQueue(this._queue);
var query = {};
for(var key in this._options.query) {
query[key] = this._options.query[key];
}
var queryParts = [];
for (var i in query) {
if (!query.hasOwnProperty(i)) continue;
queryParts.push(i + '=' + query[i]);
}
var queryString = queryParts.join('&');
this._http.post({
body: body,
url: this._endpoint + "?" + queryString,
cookies: this._options.cookies,
clientId: this._options.clientId,
secret: this._options.secret,
headers: this._options.headers || {},
timeStart: this._queueTimeStart
})
.then(parseResponseBody)
.then(resolveQueue.bind(this, this._queue))
.catch(rejectQueue.bind(this, this._queue));
this.resetQueue();
};
// Parses the body of a JSON response and returns an
// array of objects.
var parseResponseBody = function(response) {
var results = [];
var responses = JSON.parse(response.body);
// exceptions will be bubbled up
for (var i in responses) {
results.push(JSON.parse(responses[i]));
}
return results;
};
// Resolves all queued promises with the associated
// result from the API response.
var resolveQueue = function(queue, results) {
for (var i in queue) {
var result = results[i];
// If the API returns nothing then assume it's ok.
if (result == null) {
result = {
result: null,
stat: 'ok'
};
}
if (result.stat && this._events.hasOwnProperty(result.stat)) {
for (var b in this._events[result.stat]) {
this._events[result.stat][b](queue[i], result);
}
}
if (result.stat && result.stat !== 'ok') {
queue[i].deferred.reject(result);
} else {
queue[i].deferred.resolve(result);
}
}
return results;
};
// Rejects all the queued promises with the provided
// error.
var rejectQueue = function(queue, error) {
for (var i in queue) {
queue[i].deferred.reject(error);
}
return error;
};
// Clears the queue of API calls and the batch timeout.
TaggedApi.prototype.resetQueue = function() {
if (null !== this._batchTimeout) {
clearTimeout(this._batchTimeout);
this._batchTimeout = null;
}
this._queue = [];
};
TaggedApi.prototype.on = function(stat, callback) {
if (!this._events.hasOwnProperty(stat)) {
this._events[stat] = [];
}
this._events[stat].push(callback);
};
/**
* @param {string} url - Host url of API
* @param {object} options
* @param {string} requestProp - Property name of the request (req)
*/
TaggedApi.middleware = function(url, options, requestProp = 'api') {
var NodeAdapter = require('./http_adapter/node');
var http = new NodeAdapter();
return function(req, res, next) {
var newOpts = {
query: {
application_id: 'user',
format: 'JSON'
},
params: {
api_signature: ''
},
cookies: req.headers && req.headers.cookie,
headers: {}
};
if (options && options.passHeaders) {
for (var i = 0, j = options.passHeaders.length; i < j; i++) {
var header = options.passHeaders[i];
if (req.headers.hasOwnProperty(header)) {
newOpts.headers[header] = req.headers[header];
}
}
}
req[requestProp] = new TaggedApi(url, mergeRecursive(newOpts, options || {}), http);
next();
};
};
// Transforms the post data into the format required by the API
var stringifyQueue = function(queue) {
// Each API call will be transformed into a string of
// key/value pairs and placed into this array.
var calls = [];
for (var i in queue) {
var call = stringifyCall(queue[i]);
calls.push(call);
}
return "\n" + calls.join("\n") + "\n";
};
var stringifyCall = function(call) {
// Each key/value pair of the API call will be placed
// into this params array as a `key=value` string.
var params = ["method=" + encodeURIComponent(call.method)];
// Add each custom param to the params array as a
// `key=value` string.
for (var key in call.params) {
// Passing `null` as a value is not supported by
// the API, so omit those values.
//TODO: support arrays as values
if (null !== call.params[key] && call.params.hasOwnProperty(key)) {
params.push(parameterize(key, call.params[key]));
}
}
// All params are joined by `&`, resulting in a single
// one-line string to represent the API call.
return params.join('&');
};
var getHighResolutionTimeStamp = function() {
if (typeof(process) !== 'undefined' && typeof process.hrtime === 'function') {
// Node environment
return process.hrtime();
} else if (window && window.performance && typeof window.performance.now === 'function') {
// Browser envorinment that supports high-resolution timestamps
// Must convert from float to nodejs-flavored high-resolution timestamp
// @see https://nodejs.org/api/process.html#process_process_hrtime_time
// @see https://developer.mozilla.org/en-US/docs/Web/API/Performance/now
var now = window.performance.now().toString();
if (now.match(/^[0-9]+\.[0-9]+$/)) {
return now.split('.').map(function(value) {
return parseInt(value);
});
}
}
// High resolution timestamps are not supported,
// or returned an unexpected result.
// Fall back to low-resolution timestamp.
return [new Date().getTime(), 0];
}
var parameterize = function(key, value) {
var type = typeof value;
switch (type) {
case 'string':
case 'number':
case 'boolean':
return parameterizePrimitive(key, value);
break;
case 'undefined':
return parameterizePrimitive(key, '');
break;
case 'object':
// `null` is considered an "object"
return (null === value) ? parameterizePrimitive(key, value) : parameterizeObject(key, value);
break;
default:
throw new Error("Unable to parameterize key " + key + " with type " + type);
}
};
var parameterizePrimitive = function(key, value) {
// Keys and values must be encoded to
// prevent accidental breakage of string
// splits by `=` and `&`.
return encodeURIComponent(key) + "=" + encodeURIComponent(value);
};
var parameterizeObject = function(key, value) {
var params = [];
if (Array.isArray(value)) {
for (var i = 0, len = value.length; i < len; i++) {
params.push(encodeURIComponent(key) + "[]=" + encodeURIComponent(value[i]));
}
} else {
// assume object
for (var subkey in value) {
if (!value.hasOwnProperty(subkey)) continue;
params.push(encodeURIComponent(key) + "[" + encodeURIComponent(subkey) + "]=" + encodeURIComponent(value[subkey]));
}
}
return params.join('&');
};
// Recursively merge properties of two objects
// Adapted from http://stackoverflow.com/a/383245/249394
function mergeRecursive(obj1, obj2) {
for (var p in obj2) {
if (!obj2.hasOwnProperty(p)) {
continue;
}
try {
// Property in destination object set; update its value.
if (obj2[p].constructor === Object) {
obj1[p] = mergeRecursive(obj1[p], obj2[p]);
} else {
obj1[p] = obj2[p];
}
} catch(e) {
// Property in destination object not set; create it and set its value.
obj1[p] = obj2[p];
}
}
return obj1;
}
if (typeof exports !== 'undefined') {
// We're in a nodejs environment, export this module
module.exports = TaggedApi;
} else {
// We're in a browser environment, expose this module globally
context.TaggedApi = TaggedApi;
}
})();
// This file may run in a browser, so wrap it in an IIFE.
(function() {
var VanillaAdapter = function(XMLHttpRequest, Promise) {
this._xmlhttprequest = XMLHttpRequest;
this._headers = {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
};
this._promise = Promise;
this._timeout = 10000;
};
VanillaAdapter.prototype.setTimeout = function(timeout) {
this._timeout = parseInt(timeout, 10) || timeout;
};
VanillaAdapter.prototype.setHeader = function(key, value) {
this._headers[key] = value;
};
VanillaAdapter.prototype.setHeaders = function(headers) {
for (var key in headers) {
if (!headers.hasOwnProperty(key)) {
continue;
}
this.setHeader(key, headers[key]);
}
};
VanillaAdapter.prototype.post = function(req) {
return new this._promise(function(resolve, reject) {
var xhr = new this._xmlhttprequest();
xhr.open('POST', req.url, true);
Object.keys(this._headers).forEach(function(key) {
xhr.setRequestHeader(key, this._headers[key]);
}.bind(this));
xhr.timeout = this._timeout;
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) return;
try {
var response = { body: xhr.responseText };
} catch (e) {
reject(e);
}
resolve(response);
};
xhr.send(req.body);
}.bind(this));
};
if (typeof exports !== 'undefined') {
// We're in a nodejs environment, export this module
module.exports = VanillaAdapter;
} else {
// We're in a browser environment, expose this module globally
TaggedApi.VanillaAdapter = VanillaAdapter;
}
})();