This repository has been archived by the owner on Apr 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsndapi.js
executable file
·461 lines (414 loc) · 16.8 KB
/
sndapi.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
/**
* sndapi-js - SND news API ajax call wrapper for the browser
* @version v1.0.2
* @link https://bitbucket.org/schibstednorge/snd-api-js
* @license BSD-2-Clause
*/
/*global global,ActiveXObject */
//noinspection ThisExpressionReferencesGlobalObjectJS
(function(global) {
"use strict";
/**
* Creates a new SchoenfinkelizedResult object with empty callback lists and unresolved state.
* @constructor
* @memberOf SNDAPI.prototype
* @classdesc This represents a result in form of a promise, that you can _curry_
* (or _schönfinkelize_, hence the name) to attach as many handlers as you need and when you need them.
* @returns {SchoenfinkelizedResult}
*/
function SchoenfinkelizedResult() {
if (!(this instanceof SchoenfinkelizedResult)) {
return new SchoenfinkelizedResult();
}
// instance properties
this._onSuccess = [];
this._onError = [];
// enabling firing callback after promise resolution
this._state = 0; // 1 - cool, 2 - not cool
this._resolution = null;
}
SchoenfinkelizedResult.prototype = {
/**
* Add success callback to the AJAX call.
* @param callback {function} This will be called if the request completes successfully
* @returns {SchoenfinkelizedResult} self.
*/
success: function(callback) {
this._onSuccess.push(callback);
this._refire();
return this;
},
/**
* Add fail (error/timeout) callback to the AJAX call
*
* @param callback {function} This will be called if the request fails
* @returns {SchoenfinkelizedResult} self.
*/
fail: function(callback) {
this._onError.push(callback);
this._refire();
return this;
},
/**
* Used by the library to resolve the promise with a successful result
* @param {...object} all parameters will be passed to success listeners
* @returns {SchoenfinkelizedResult} self.
*/
resolve: function() {
var cb, args = this._resolution || arguments;
this._state = 1;
this._resolution = args;
while (!!(cb = this._onSuccess.shift())) {
cb.apply(this, args);
}
return this;
},
/**
* Used by the library to resolve the promise with an unsuccessful result
* @param {...object} all parameters will be passed to fail listeners
* @returns {SchoenfinkelizedResult} self.
*/
reject: function() {
var cb, args = this._resolution || arguments;
this._state = 2;
this._resolution = args;
while (!!(cb = this._onError.shift())) {
cb.apply(this, args);
}
return this;
},
/**
* Used internally. Delegates the responsibilities to another SchoenfinkelizedResult.
*
* We are using this when the operation is not done immediately, but instead
* queued for later (when we have a valid token). We must reuse the handlers
* that are *and will be (in the future)* attached to the original result to
* fire them, when the new, internally called with .ajax again, operation ends.
*
* What it actually does is take the other listener array *references*
* and plug them in here, concatenating all listeners.
*
* @param otherResult
* @internal
* @returns {SchoenfinkelizedResult} self.
*/
handleWith: function(otherResult) {
this._onSuccess.forEach(function(item) { otherResult._onSuccess.push(item); });
this._onError.forEach(function(item) { otherResult._onError.push(item); });
this._onSuccess = otherResult._onSuccess; // use the reference
this._onError = otherResult._onError; // use the reference
this._refire();
return this;
},
/**
* If the promise was resolved before (either good or bad way, whatever),
* fire the appropriate, late-defined callbacks!
*
* @private
*/
_refire: function() {
if (this._state > 0) {
// we know the outcome
if (this._state === 1) {
// if it's good, fire good stuff callbacks.
this.resolve();
} else {
// if it's bad, fire the one responsible.
this.reject();
}
}
}
};
/**
* Call wrapper for signing the SND news API ajax request. Registers as global SNDAPI constructor.
* @global
* @constructor
* @alias SNDAPI
* @param options {object} Options object
* @param options.signatureServiceUrl {string?} URL for the signature service
* @param options.prefixUrl {string?} Common prefix for all URLs called later by the API (you can use partial URLs later)
* @param options.key {string} API key of your client
*/
global.SNDAPI = global.SNDAPI || function(options) {
var apiOptions = mergeOptions({
signatureServiceUrl: "//api.schibsted.tech/proxy/sts/v3/signature",
prefixUrl : "//api.schibsted.tech/content/v3/",
key : null
}, options),
publicApi,
state = {
token : null,
tokenTimer: null
},
queue = [];
/**
* Fetches an object representing the current state of the library.
* @memberOf SNDAPI
* @public
* @instance
* @returns {{tokenIsSet: boolean, tokenTimerIsSet: boolean}}
*/
function getState() {
return {
/**
* is the token/signature set (received correctly from the server?)
*/
tokenIsSet : !!(state.token),
/**
* tells if the timer to refresh token automatically is set correctly (for debug)
*/
tokenTimerIsSet: !!(state.tokenTimer)
};
}
/**
* initializes the SND API and fetches a new token from the server
* @param options {object} request parameters
* @param [options.async=true] {boolean} make init asynchronous (non-blocking)
* @memberOf SNDAPI
* @instance
*/
function init(options) {
if (!apiOptions.key) {
throw new Error("API key is required for SND API initialization");
}
return refreshToken(options);
}
function nextFullHour() {
var deadline;
deadline = new Date();
deadline.setHours(deadline.getHours()+1);
deadline.setMinutes(0);
deadline.setSeconds(0);
deadline.setMilliseconds(0);
return deadline;
}
/**
* refreshes the token/signature contacting the signature service
* @param options {object} request parameters
* @param [options.async=true] {boolean} make this request asynchronous (non-blocking)
* @returns {*}
*/
function refreshToken(options) {
var requestOptions = mergeOptions({
// the defaults:
async: true
}, options);
requestOptions = mergeOptions(requestOptions, {
sign: false,
url : apiOptions.signatureServiceUrl + "?api-key=" + apiOptions.key
});
// set up next refresh
if (state.tokenTimer) {
clearTimeout(state.tokenTimer);
}
state.tokenTimer = setTimeout(refreshToken, nextFullHour()-(new Date()));
return ajax(requestOptions)
.success(function(response, statusDetails) {
var request;
state.token = response.token;
if (queue.length) {
while ((request = queue.shift())) {
ajax(request.options).handleWith(request.result);
}
}
})
.fail(function(error) {
// TODO handle it? or leave it to the user?
});
}
/**
* Overwrite default options with given ones and return them in a new object (shallow copying here).
* @param defaults {object} Your map of default values for options
* @param given {object?} Options given in this particular method call, can be undefined
* @returns {object} A new object with shallow copy of defaults overwritten with shallow copy of given options
* @private
* @instance
*/
function mergeOptions(defaults, given) {
var key, result = {}, hop = Object.hasOwnProperty;
for (key in defaults) {
if (hop.call(defaults, key)) {
//noinspection JSUnfilteredForInLoop
result[key] = defaults[key];
}
}
if (typeof given === "object") {
for (key in given) {
if (hop.call(given, key) && given[key] !== undefined) {
//noinspection JSUnfilteredForInLoop
result[key] = given[key];
}
}
}
return result;
}
/**
* Make an AJAX call for any data
* @param options {object} request parameters
* @param options.url {string} request URL, will be prefixed with prefixUrl passed to constructor if relative
* @param options.postData {object?} data that will be sent as POST body
* @param [options.preferJSON=true] (boolean) do we want to add header asking politely for JSON content-type?
* It will be parsed automatically, if valid.
* @param [options.sign=true] {boolean} sign this request with the x-snd-apisignature header
* @param [options.async=true] {boolean} make this request asynchronous (non-blocking)
* @param [options.timeout=30e3] {number} if request doesn't respond within this many milliseconds, fail.
* @param [options.retries=2] {retries} if request fails, refresh token and retry this many times.
* @memberOf SNDAPI
* @instance
* @returns {SchoenfinkelizedResult} a promise
*/
function ajax(options) {
var requestOptions = mergeOptions({
// the defaults:
async : true,
url : null,
postData : null,
contentType: null,
preferJSON : true,
sign : true,
timeout : 30e3,
retries : 2
}, options),
req = createXMLHTTPObject(),
method = (requestOptions.postData) ? "POST" : "GET",
status = null,
statusDetails = {
response: null
},
result = new SchoenfinkelizedResult();
if (!/^([a-z]+:)?\/\//.test(requestOptions.url)) {
// prepend the standard prefix
requestOptions.url = apiOptions.prefixUrl + requestOptions.url;
}
function resolve() {
clearTimeout(req._timeouter);
if (status === "success") {
return result.resolve(statusDetails.response, statusDetails);
} else {
return result.reject(statusDetails);
}
}
if (!req) {
status = "fail";
return result;
}
result.req = req; // publish the object, why not
// no matter if we're going to queue or not, timeout should start now
req._timeouter = setTimeout(function() {
status = "fail";
statusDetails = {
statusCode: -1,
statusText: "Request timed out",
response : null
};
result.reject(statusDetails);
}, requestOptions.timeout);
// queue if we are not ready
if (!state.token && requestOptions.sign) {
queue.push({
options: requestOptions,
result : result
});
return result;
}
// otherwise make the request
req.open(method, requestOptions.url, requestOptions.async);
// no idea why this was in stackOverflow code
// req.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
// adding signature
if (state.token && requestOptions.sign) {
req.setRequestHeader('X-Snd-Apisignature', state.token);
req.setRequestHeader('X-Snd-Apikey', apiOptions.key);
}
if (requestOptions.postData) {
if (requestOptions.contentType && requestOptions.contentType != null) {
req.setRequestHeader('Content-type', requestOptions.contentType);
} else {
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
}
if (requestOptions.preferJSON) {
req.setRequestHeader('Accept', 'application/json');
}
req.onreadystatechange = function() {
if (req.readyState !== 4) { return; }
if (req.status !== 200 && req.status !== 304) {
if (req.status === 403) {
// invalid security key, most likely
// retry. maybe a very unfortunate timing.
state.token = null;
if (requestOptions.retries) {
// some retries still left
requestOptions.retries--;
return ajax(requestOptions);
}
}
status = "fail";
statusDetails = {
statusCode: req.status,
statusText: req.statusText,
response : req.responseText
};
} else {
status = "success";
statusDetails = {
statusCode: req.status,
statusText: req.statusText,
response : req.responseText
};
if (req.getResponseHeader("Content-Type").match(/^application\/json/) && JSON) {
try {
statusDetails.response = JSON.parse(statusDetails.response);
} catch (e) {
// do not parse :D
}
}
}
resolve();
};
if (req.readyState === 4) {
if (global.console) {global.console.warn("I did not expect to get here");}
return null;
}
try {
req.send(requestOptions.postData);
} catch (e) {
// sync/immediate error handling
status = "fail";
statusDetails = {
statusCode: e.code || 0,
statusText: e.message || "Error caught when trying to send request",
response : e
};
resolve();
}
return result;
}
var XMLHttpFactories = [
function() {return new XMLHttpRequest();},
function() {return new ActiveXObject("Msxml2.XMLHTTP");},
function() {return new ActiveXObject("Msxml3.XMLHTTP");},
function() {return new ActiveXObject("Microsoft.XMLHTTP");}
];
function createXMLHTTPObject() {
var XmlHttp = false;
for (var i = 0; i < XMLHttpFactories.length; i++) {
try { XmlHttp = XMLHttpFactories[i](); }
catch (e) { continue; }
break;
}
return XmlHttp;
}
publicApi = {
init : init,
getState: getState,
ajax : ajax
};
return publicApi;
};
global.SNDAPI.prototype.SchoenfinkelizedResult = SchoenfinkelizedResult;
})(typeof global === "object" ? global : this);
/*global module,SNDAPI */
if (typeof module !== 'undefined' && module.exports) {
module.exports = SNDAPI;
}