-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub-ajax.html
More file actions
560 lines (501 loc) · 16.5 KB
/
github-ajax.html
File metadata and controls
560 lines (501 loc) · 16.5 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
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
<!--
@license
Copyright (c) 2017 Preview-Code. All rights reserved.
This code may only be used under the BSD style license found in LICENSE.txt
-->
<link rel="import" href="../polymer/polymer.html">
<!--
@demo demo/index.html
-->
<dom-module id="github-ajax">
<template>
</template>
<script>
(function() {
var sharedToken;
var instances = [];
Polymer({
is: 'github-ajax',
properties: {
/**
* Reflects whether every page of results has been loaded.
* If false, call `fetchMore()` to load the next page of results.
*
* The accumulated results are stored in `allResults`.
* `lastResponse` will only contain the data received from the last requested page.
*
* The amount of results loaded depends on the `perPage` property,
* as well as on whether GitHub decides to honor the value you set in `perPage`.
* @type {Boolean}
*/
canFetchMore: {
type: Boolean,
readOnly: true,
notify: true,
value: true
},
/**
* Stores accumulated results from all fetched pages.
* If the endpoint you query only returns one result, this array wil contain simply that result.
*
* Calling `generateRequest()` will reset this array.
* @type {Array}
*/
allResults: {
type: Array,
readOnly: true,
notify: true,
value: () => []
},
/**
* How many results must be retrieved from GitHub, default 10.
* @type {Number}
*/
perPage: {
type: Number,
observer: '_onPerPageChange'
},
/**
* OAuth access token for authenticated requests, e.g.: fetching the current user.
* This property will automatically be shared between all attached instances of `github-ajax`.
* @type {String}
*/
accessToken: {
type: String,
observer: '_onTokenChange'
},
/**
* Amount of milliseconds before the request is considered to be timed out.
* A timeout triggers the `github-error` event and sets the appropriate lastError and lastRequest property.
*
* Note that the timeout property cannot cancel the actual in-flight request,
* since the Fetch API does not yet have support for interrupting requests.
*
* @type {Number}
*/
timeout: {
type: Number,
value: null
},
/**
* The url to query, e.g.: https://api.github.com/users
* @type {String}
*/
url: {
type: String,
observer: '_resetPagination'
},
/**
* URL query parameters to send with the request.
* Parameter keys are represented by the object field names,
* param values are the values for object fields.
* @type{Object}
*/
params: {
type: Object,
value: function() { return {} }
},
/**
* The request method to use. Defaults to `GET`.
* @type {String}
*/
method: {
type: String,
value: 'GET',
observer: '_resetPagination'
},
/**
* Request headers to send with the request.
* Header keys are represented by the object field names,
* header values are the values for object fields.
* Note: setting a `Content-Type` header here will override the value
* specified by the `contentType` property of this element.
* @type {Object}
*/
headers: {
type: Object,
value: function() { return {} }
},
/**
* Content type to use when sending data. If the `contentType` property
* is set and a `Content-Type` header is specified in the `headers`
* property, the `headers` property value will take precedence.
*
* Varies the handling of the `body` param.
* @type {String}
*/
contentType: {
type: String,
value: null,
observer: '_resetPagination'
},
/**
* Body content to send with the request, typically used with "POST"
* requests.
*
* If body is a string it will be sent unmodified.
* If the body is a string and contentType is not set,
* then the `content-type` will default to `application/x-www-form-urlencoded"`
*
* If Content-Type is set to a value listed below, then
* the body will be encoded accordingly.
*
* * `content-type="application/json"`
* * body is encoded like `{"foo":"bar baz","x":1}`
* * `content-type="application/x-www-form-urlencoded"`
* * body is encoded like `foo=bar+baz&x=1`
*
* Otherwise the body will be passed to the browser unmodified, and it
* will handle any encoding (e.g. for FormData, Blob, ArrayBuffer).
*
* @type (ArrayBuffer|ArrayBufferView|Blob|Document|FormData|null|string|undefined|Object)
*/
body: {
type: Object,
value: null,
observer: '_resetPagination'
},
/**
* Specifies what data to store in the response, and
* to deliver in `response` events.
*
* One of:
*
* `text`: uses `response.text()`.
*
* `json`: uses `response.json()`.
*
* `arraybuffer`: uses `response.arrayBuffer()`.
*
* Any other value will result in an error on response.
*/
handleAs: {
type: String,
value: 'json',
observer: '_resetPagination'
},
/**
* The most recent request made by this iron-ajax element.
* @type {Request}
*/
lastRequest: {
type: Object,
notify: true,
readOnly: true
},
/**
* True while lastRequest is in flight.
*/
loading: {
type: Boolean,
notify: true,
readOnly: true,
},
/**
* The most recent request made by this iron-ajax element.
* Note that lastResponse and lastError are set when lastRequest finishes,
* so if loading is true, then lastResponse and lastError will correspond
* to the result of the previous request.
*
* The type of the response is determined by the value of `handleAs` at
* the time that the request was generated.
*/
lastResponse: {
type: Object,
notify: true,
readOnly: true
},
/**
* lastRequest's error, if any.
*
* @type {Object}
*/
lastError: {
type: Object,
notify: true,
readOnly: true
},
_nextPageLink: {
type: String
}
},
observers: [
'_resetPagination(params.*, headers.*)'
],
attached: function() {
if (sharedToken) this.accessToken = sharedToken;
instances.push(this);
},
detached: function() {
instances.splice(instances.indexOf(this), 1);
},
_onPerPageChange: function(itemCount) {
if (this.params) this.params['per_page'] = itemCount;
this._resetPagination();
},
_onTokenChange: function(newToken) {
if (newToken !== sharedToken) {
sharedToken = newToken;
instances.forEach(function(instance) {
instance.accessToken = sharedToken;
});
}
if (this.params) this.params['access_token'] = newToken;
},
/**
* The query string that should be appended to the `url`, serialized from
* the current value of `params`.
*
* @return {string}
*/
get queryString () {
const queryParts = [];
var param;
var value;
for (param in this.params) {
value = this.params[param];
param = window.encodeURIComponent(param);
if (Array.isArray(value)) {
for (var i = 0; i < value.length; i++) {
queryParts.push(param + '=' + window.encodeURIComponent(value[i]));
}
} else if (value !== null) {
queryParts.push(param + '=' + window.encodeURIComponent(value));
} else {
queryParts.push(param);
}
}
return queryParts.join('&');
},
/**
* The `url` with query string (if `params` are specified).
*
* @return {string}
*/
get requestUrl() {
if (sharedToken && this.accessToken !== sharedToken) {
this.accessToken = sharedToken;
}
const queryString = this.queryString;
const url = this.url || '';
if (queryString) {
const bindingChar = url.indexOf('?') >= 0 ? '&' : '?';
return url + bindingChar + queryString;
}
return url;
},
/**
* An object that maps header names to header values, first applying the
* the value of `Content-Type` and then overlaying the headers specified
* in the `headers` property.
*
* @return {Object}
*/
get requestHeaders() {
const headers = new Headers();
var contentType = this.contentType;
if (contentType === null && (typeof this.body === 'string')) {
contentType = 'application/x-www-form-urlencoded';
}
if (contentType) {
headers.set('content-type', contentType);
}
var acceptType = {
'json': 'application/json',
'text': 'text/plain',
'html': 'text/html',
'arraybuffer': 'application/octet-stream'
}[this.handleAs];
var header;
if (this.headers instanceof Object) {
for (header in this.headers) {
headers.set(header, this.headers[header].toString());
}
if (acceptType && !headers.has('Accept')) {
headers.set('Accept', acceptType);
}
}
return headers;
},
/**
* @param {Object} object The object to encode as x-www-form-urlencoded.
* @return {string} .
*/
_wwwFormUrlEncode: function(object) {
if (!object) {
return '';
}
var pieces = [];
Object.keys(object).forEach(function(key) {
pieces.push(
this._wwwFormUrlEncodePiece(key) + '=' +
this._wwwFormUrlEncodePiece(object[key]));
}, this);
return pieces.join('&');
},
/**
* @param {*} str A key or value to encode as x-www-form-urlencoded.
* @return {string} .
*/
_wwwFormUrlEncodePiece: function(str) {
// Spec says to normalize newlines to \r\n and replace %20 spaces with +.
// jQuery does this as well, so this is likely to be widely compatible.
if (str === null) {
return '';
}
return encodeURIComponent(str.toString().replace(/\r?\n/g, '\r\n'))
.replace(/%20/g, '+');
},
_encodeBody: function(headers) {
if (!this.body) {
return;
} else if (headers.has('content-type') &&
headers.get('content-type') === 'application/x-www-form-urlencoded' &&
typeof this.body === 'object') {
return this._wwwFormUrlEncode(this.body);
} else if (this.body instanceof FormData
|| this.body instanceof ArrayBuffer
|| typeof this.body === 'string') {
return this.body;
} else {
return JSON.stringify(this.body)
}
},
/**
* Performs an AJAX request to the specified URL.
* This will reset the results stored in `allResults`.
* If the queried endpoint supports pagination, the first page will be loaded.
*
* Returns a Promise that resolves when the request completes and after any events have been fired.
* @return {Promise}
*/
generateRequest: function() {
this._setAllResults([]);
return this._generateRequest(this.requestUrl);
},
/**
* If `canFetchMore` returns true, this method will
* request the next page of results.
* These results will be concatenated to `allResults`.
*
* Returns a Promise that resolves when the request completes and after any events have been fired.
* Just like `generateRequest`, this method will fire `github-response` & co events.
* @return {Promise}
*/
fetchMore: function() {
if (this.canFetchMore) {
if (this._nextPageLink) {
return this._generateRequest(this._nextPageLink);
} else {
return this.generateRequest();
}
}
},
_appendResults: function(responseBody) {
if (!responseBody) return;
this._setAllResults(this.allResults.concat(responseBody));
this._onResponse(responseBody);
},
_generateRequest: function(url) {
const headers = this.requestHeaders
const request = new Request(url, {
method: this.method,
headers: headers,
body: this._encodeBody(headers)
});
return this._fetchOrTimeout(request)
.then(this._checkResponseForErrors.bind(this))
.then(this._decodeResponseBody.bind(this))
.then(this._appendResults.bind(this))
.then(this._onResponse.bind(this))
.catch(error => {
this._onError(error);
throw error;
});
},
_fetchOrTimeout: function(request) {
this._setLastRequest(request);
this._setLoading(true);
this.fire('github-request', request);
return Promise.race([this._timeout(), fetch(request).then(response => ({
request: request,
response: response
}))]);
},
_timeout: function() {
return new Promise((resolve, reject) => {
if (this.timeout) {
setTimeout(() => reject({timeout: true, message: 'The request timed out'})
, this.timeout);
}
});
},
_checkResponseForErrors: function(o) {
if (this.lastRequest === o.request) {
if (o.response.ok) {
return Promise.resolve(o.response);
} else {
return Promise.reject({
message: o.response.statusText,
errorCode: o.response.status,
response: o.response
});
}
}
},
_decodeResponseBody: function(response) {
if (!response) return;
var body;
if (this.handleAs === 'json') {
body = response.json();
} else if (this.handleAs === 'text') {
body = response.text();
} else if (this.handleAs === 'arrayBuffer') {
body = response.arrayBuffer();
} else {
throw new Error('Unrecognized `handleAs` property: ' + this.handleAs);
}
this._updatePagination(response.headers.get('Link'));
return body;
},
_resetPagination: function() {
this._setCanFetchMore(true);
this._nextPageLink = undefined;
},
_updatePagination: function(linkHeader) {
const pageLinks = this._parseLinkHeader(linkHeader);
if (pageLinks.next) {
this._setCanFetchMore(true);
this._nextPageLink = pageLinks.next;
} else {
this._setCanFetchMore(false);
this._nextPageLink = undefined;
}
},
_parseLinkHeader: function(linkHeader) {
const pageLinks = {}
if (linkHeader) {
linkHeader.split(',').forEach(link => {
const linkMatches = link.match(/<(.+)>; rel="(next|prev|first|last)"/);
if (linkMatches && linkMatches.length >= 3) pageLinks[linkMatches[2]] = linkMatches[1];
});
}
return pageLinks;
},
_onResponse: function(responseBody) {
if (!responseBody) return;
this._setLoading(false);
this._setLastError(null);
this._setLastResponse(responseBody);
this.fire('github-response', responseBody);
},
_onError: function(err) {
this._setLoading(false);
this._setLastResponse(null);
this._setLastError(err);
this.fire('github-error', err);
}
});
})();
</script>
</dom-module>