Blame view

bower_components/iron-ajax/iron-ajax.html 12.5 KB
73bcce88   luigser   COMPONENTS
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
  <!--
  Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
  This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
  The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
  The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
  Code distributed by Google as part of the polymer project is also
  subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
  -->
  
  <link rel="import" href="../polymer/polymer.html">
  <link rel="import" href="iron-request.html">
  
  <!--
  The `iron-ajax` element exposes network request functionality.
  
      <iron-ajax
          auto
          url="http://gdata.youtube.com/feeds/api/videos/"
          params='{"alt":"json", "q":"chrome"}'
          handle-as="json"
          on-response="handleResponse"
          debounce-duration="300"></iron-ajax>
  
  With `auto` set to `true`, the element performs a request whenever
  its `url`, `params` or `body` properties are changed. Automatically generated
  requests will be debounced in the case that multiple attributes are changed
  sequentially.
  
  Note: The `params` attribute must be double quoted JSON.
  
  You can trigger a request explicitly by calling `generateRequest` on the
  element.
  
  @demo demo/index.html
  @hero hero.svg
  -->
  
  <script>
    'use strict';
  
    Polymer({
  
      is: 'iron-ajax',
  
      /**
       * Fired when a request is sent.
       *
       * @event request
       */
  
      /**
       * Fired when a response is received.
       *
       * @event response
       */
  
      /**
       * Fired when an error is received.
       *
       * @event error
       */
  
e619a3b0   Luigi Serra   Controllet cross ...
63
64
65
66
      hostAttributes: {
        hidden: true
      },
  
73bcce88   luigser   COMPONENTS
67
68
69
70
71
      properties: {
        /**
         * The URL target of the request.
         */
        url: {
f748e9cf   Luigi Serra   new controllet an...
72
          type: String
73bcce88   luigser   COMPONENTS
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
        },
  
        /**
         * An object that contains query parameters to be appended to the
         * specified `url` when generating a request. If you wish to set the body
         * content when making a POST request, you should use the `body` property
         * instead.
         */
        params: {
          type: Object,
          value: function() {
            return {};
          }
        },
  
        /**
         * The HTTP method to use such as 'GET', 'POST', 'PUT', or 'DELETE'.
         * Default is 'GET'.
         */
        method: {
          type: String,
          value: 'GET'
        },
  
        /**
         * HTTP request headers to send.
         *
         * Example:
         *
         *     <iron-ajax
         *         auto
         *         url="http://somesite.com"
         *         headers='{"X-Requested-With": "XMLHttpRequest"}'
         *         handle-as="json"></iron-ajax>
         *
         * Note: setting a `Content-Type` header here will override the value
         * specified by the `contentType` property of this element.
         */
        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.
         */
        contentType: {
          type: String,
          value: null
        },
  
        /**
         * Body content to send with the request, typically used with "POST"
         * requests.
         *
         * If body is a string it will be sent unmodified.
         *
         * 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
        },
  
        /**
         * Toggle whether XHR is synchronous or asynchronous. Don't change this
         * to true unless You Know What You Are Doing™.
         */
        sync: {
          type: Boolean,
          value: false
        },
  
        /**
         * Specifies what data to store in the `response` property, and
         * to deliver as `event.detail.response` in `response` events.
         *
         * One of:
         *
         *    `text`: uses `XHR.responseText`.
         *
         *    `xml`: uses `XHR.responseXML`.
         *
         *    `json`: uses `XHR.responseText` parsed as JSON.
         *
         *    `arraybuffer`: uses `XHR.response`.
         *
         *    `blob`: uses `XHR.response`.
         *
         *    `document`: uses `XHR.response`.
         */
        handleAs: {
          type: String,
          value: 'json'
        },
  
        /**
         * Set the withCredentials flag on the request.
         */
        withCredentials: {
          type: Boolean,
          value: false
        },
  
        /**
eb240478   Luigi Serra   public room cards...
193
194
195
196
197
198
199
200
         * Set the timeout flag on the request.
         */
        timeout: {
          type: Number,
          value: 0
        },
  
        /**
73bcce88   luigser   COMPONENTS
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
         * If true, automatically performs an Ajax request when either `url` or
         * `params` changes.
         */
        auto: {
          type: Boolean,
          value: false
        },
  
        /**
         * If true, error messages will automatically be logged to the console.
         */
        verbose: {
          type: Boolean,
          value: false
        },
  
        /**
e619a3b0   Luigi Serra   Controllet cross ...
218
         * The most recent request made by this iron-ajax element.
73bcce88   luigser   COMPONENTS
219
         */
e619a3b0   Luigi Serra   Controllet cross ...
220
221
        lastRequest: {
          type: Object,
73bcce88   luigser   COMPONENTS
222
223
224
225
226
          notify: true,
          readOnly: true
        },
  
        /**
e619a3b0   Luigi Serra   Controllet cross ...
227
         * True while lastRequest is in flight.
73bcce88   luigser   COMPONENTS
228
         */
e619a3b0   Luigi Serra   Controllet cross ...
229
230
        loading: {
          type: Boolean,
73bcce88   luigser   COMPONENTS
231
232
233
234
235
          notify: true,
          readOnly: true
        },
  
        /**
e619a3b0   Luigi Serra   Controllet cross ...
236
237
238
239
240
241
242
243
         * lastRequest's response.
         *
         * 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.
a1a3bc73   Luigi Serra   graphs updates
244
         *
f748e9cf   Luigi Serra   new controllet an...
245
         * @type {Object}
73bcce88   luigser   COMPONENTS
246
247
248
249
250
251
252
253
         */
        lastResponse: {
          type: Object,
          notify: true,
          readOnly: true
        },
  
        /**
e619a3b0   Luigi Serra   Controllet cross ...
254
         * lastRequest's error, if any.
a1a3bc73   Luigi Serra   graphs updates
255
         *
f748e9cf   Luigi Serra   new controllet an...
256
         * @type {Object}
73bcce88   luigser   COMPONENTS
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
         */
        lastError: {
          type: Object,
          notify: true,
          readOnly: true
        },
  
        /**
         * An Array of all in-flight requests originating from this iron-ajax
         * element.
         */
        activeRequests: {
          type: Array,
          notify: true,
          readOnly: true,
          value: function() {
            return [];
          }
        },
  
        /**
a1a3bc73   Luigi Serra   graphs updates
278
         * Length of time in milliseconds to debounce multiple automatically generated requests.
73bcce88   luigser   COMPONENTS
279
280
281
282
283
284
285
         */
        debounceDuration: {
          type: Number,
          value: 0,
          notify: true
        },
  
a1a3bc73   Luigi Serra   graphs updates
286
287
288
289
290
291
292
293
294
295
296
297
298
299
        /**
         * Prefix to be stripped from a JSON response before parsing it.
         *
         * In order to prevent an attack using CSRF with Array responses
         * (http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx/)
         * many backends will mitigate this by prefixing all JSON response bodies
         * with a string that would be nonsensical to a JavaScript parser.
         *
         */
        jsonPrefix: {
          type: String,
          value: ''
        },
  
73bcce88   luigser   COMPONENTS
300
301
302
303
304
305
306
307
308
        _boundHandleResponse: {
          type: Function,
          value: function() {
            return this._handleResponse.bind(this);
          }
        }
      },
  
      observers: [
a1a3bc73   Luigi Serra   graphs updates
309
310
        '_requestOptionsChanged(url, method, params.*, headers, contentType, ' +
            'body, sync, handleAs, jsonPrefix, withCredentials, timeout, auto)'
73bcce88   luigser   COMPONENTS
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
      ],
  
      /**
       * The query string that should be appended to the `url`, serialized from
       * the current value of `params`.
       *
       * @return {string}
       */
      get queryString () {
        var queryParts = [];
        var param;
        var value;
  
        for (param in this.params) {
          value = this.params[param];
          param = window.encodeURIComponent(param);
  
eb240478   Luigi Serra   public room cards...
328
329
330
331
332
333
334
335
          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);
73bcce88   luigser   COMPONENTS
336
          }
73bcce88   luigser   COMPONENTS
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
        }
  
        return queryParts.join('&');
      },
  
      /**
       * The `url` with query string (if `params` are specified), suitable for
       * providing to an `iron-request` instance.
       *
       * @return {string}
       */
      get requestUrl() {
        var queryString = this.queryString;
  
        if (queryString) {
eb240478   Luigi Serra   public room cards...
352
353
          var bindingChar = this.url.indexOf('?') >= 0 ? '&' : '?';
          return this.url + bindingChar + queryString;
73bcce88   luigser   COMPONENTS
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
        }
  
        return this.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() {
        var headers = {};
        var contentType = this.contentType;
        if (contentType == null && (typeof this.body === 'string')) {
          contentType = 'application/x-www-form-urlencoded';
        }
        if (contentType) {
f748e9cf   Luigi Serra   new controllet an...
373
          headers['content-type'] = contentType;
73bcce88   luigser   COMPONENTS
374
375
376
377
378
        }
        var header;
  
        if (this.headers instanceof Object) {
          for (header in this.headers) {
a1a3bc73   Luigi Serra   graphs updates
379
            headers[header] = this.headers[header].toString();
73bcce88   luigser   COMPONENTS
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
          }
        }
  
        return headers;
      },
  
      /**
       * Request options suitable for generating an `iron-request` instance based
       * on the current state of the `iron-ajax` instance's properties.
       *
       * @return {{
       *   url: string,
       *   method: (string|undefined),
       *   async: (boolean|undefined),
       *   body: (ArrayBuffer|ArrayBufferView|Blob|Document|FormData|null|string|undefined|Object),
       *   headers: (Object|undefined),
       *   handleAs: (string|undefined),
a1a3bc73   Luigi Serra   graphs updates
397
       *   jsonPrefix: (string|undefined),
73bcce88   luigser   COMPONENTS
398
399
400
401
       *   withCredentials: (boolean|undefined)}}
       */
      toRequestOptions: function() {
        return {
f748e9cf   Luigi Serra   new controllet an...
402
          url: this.requestUrl || '',
73bcce88   luigser   COMPONENTS
403
404
405
406
407
          method: this.method,
          headers: this.requestHeaders,
          body: this.body,
          async: !this.sync,
          handleAs: this.handleAs,
a1a3bc73   Luigi Serra   graphs updates
408
          jsonPrefix: this.jsonPrefix,
eb240478   Luigi Serra   public room cards...
409
410
          withCredentials: this.withCredentials,
          timeout: this.timeout
73bcce88   luigser   COMPONENTS
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
        };
      },
  
      /**
       * Performs an AJAX request to the specified URL.
       *
       * @return {!IronRequestElement}
       */
      generateRequest: function() {
        var request = /** @type {!IronRequestElement} */ (document.createElement('iron-request'));
        var requestOptions = this.toRequestOptions();
  
        this.activeRequests.push(request);
  
        request.completes.then(
          this._boundHandleResponse
        ).catch(
          this._handleError.bind(this, request)
        ).then(
          this._discardRequest.bind(this, request)
        );
  
        request.send(requestOptions);
  
        this._setLastRequest(request);
        this._setLoading(true);
  
        this.fire('request', {
          request: request,
          options: requestOptions
e619a3b0   Luigi Serra   Controllet cross ...
441
        }, {bubbles: false});
73bcce88   luigser   COMPONENTS
442
443
444
445
446
  
        return request;
      },
  
      _handleResponse: function(request) {
e619a3b0   Luigi Serra   Controllet cross ...
447
448
449
450
451
452
        if (request === this.lastRequest) {
          this._setLastResponse(request.response);
          this._setLastError(null);
          this._setLoading(false);
        }
        this.fire('response', request, {bubbles: false});
73bcce88   luigser   COMPONENTS
453
454
455
456
457
458
459
      },
  
      _handleError: function(request, error) {
        if (this.verbose) {
          console.error(error);
        }
  
e619a3b0   Luigi Serra   Controllet cross ...
460
461
462
463
464
465
466
467
        if (request === this.lastRequest) {
          this._setLastError({
            request: request,
            error: error
          });
          this._setLastResponse(null);
          this._setLoading(false);
        }
73bcce88   luigser   COMPONENTS
468
469
470
        this.fire('error', {
          request: request,
          error: error
e619a3b0   Luigi Serra   Controllet cross ...
471
        }, {bubbles: false});
73bcce88   luigser   COMPONENTS
472
473
474
475
476
477
478
479
      },
  
      _discardRequest: function(request) {
        var requestIndex = this.activeRequests.indexOf(request);
  
        if (requestIndex > -1) {
          this.activeRequests.splice(requestIndex, 1);
        }
73bcce88   luigser   COMPONENTS
480
481
482
483
      },
  
      _requestOptionsChanged: function() {
        this.debounce('generate-request', function() {
f748e9cf   Luigi Serra   new controllet an...
484
          if (this.url == null) {
73bcce88   luigser   COMPONENTS
485
486
487
488
489
490
491
492
493
494
495
            return;
          }
  
          if (this.auto) {
            this.generateRequest();
          }
        }, this.debounceDuration);
      },
  
    });
  </script>