Blame view

bower_components/iron-ajax/iron-request.html 12.7 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
  <!--
  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="../promise-polyfill/promise-polyfill-lite.html">
  
  <!--
  iron-request can be used to perform XMLHttpRequests.
  
      <iron-request id="xhr"></iron-request>
      ...
      this.$.xhr.send({url: url, params: params});
  -->
  <script>
    'use strict'
  
    Polymer({
      is: 'iron-request',
  
e619a3b0   Luigi Serra   Controllet cross ...
26
27
28
29
      hostAttributes: {
        hidden: true
      },
  
73bcce88   luigser   COMPONENTS
30
31
32
33
34
35
      properties: {
  
        /**
         * A reference to the XMLHttpRequest instance used to generate the
         * network request.
         *
eb240478   Luigi Serra   public room cards...
36
         * @type {XMLHttpRequest}
73bcce88   luigser   COMPONENTS
37
38
39
40
41
42
43
44
45
46
47
48
49
50
         */
        xhr: {
          type: Object,
          notify: true,
          readOnly: true,
          value: function() {
            return new XMLHttpRequest();
          }
        },
  
        /**
         * A reference to the parsed response body, if the `xhr` has completely
         * resolved.
         *
73bcce88   luigser   COMPONENTS
51
52
53
54
55
56
57
58
         * @type {*}
         * @default null
         */
        response: {
          type: Object,
          notify: true,
          readOnly: true,
          value: function() {
a1a3bc73   Luigi Serra   graphs updates
59
            return null;
73bcce88   luigser   COMPONENTS
60
61
62
63
64
          }
        },
  
        /**
         * A reference to the status code, if the `xhr` has completely resolved.
73bcce88   luigser   COMPONENTS
65
66
67
68
69
70
71
72
73
74
         */
        status: {
          type: Number,
          notify: true,
          readOnly: true,
          value: 0
        },
  
        /**
         * A reference to the status text, if the `xhr` has completely resolved.
73bcce88   luigser   COMPONENTS
75
76
77
78
79
80
81
82
83
84
85
86
         */
        statusText: {
          type: String,
          notify: true,
          readOnly: true,
          value: ''
        },
  
        /**
         * A promise that resolves when the `xhr` response comes back, or rejects
         * if there is an error before the `xhr` completes.
         *
eb240478   Luigi Serra   public room cards...
87
         * @type {Promise}
73bcce88   luigser   COMPONENTS
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
         */
        completes: {
          type: Object,
          readOnly: true,
          notify: true,
          value: function() {
            return new Promise(function (resolve, reject) {
              this.resolveCompletes = resolve;
              this.rejectCompletes = reject;
            }.bind(this));
          }
        },
  
        /**
         * An object that contains progress information emitted by the XHR if
         * available.
         *
73bcce88   luigser   COMPONENTS
105
106
107
108
109
110
111
112
113
114
115
116
117
         * @default {}
         */
        progress: {
          type: Object,
          notify: true,
          readOnly: true,
          value: function() {
            return {};
          }
        },
  
        /**
         * Aborted will be true if an abort of the request is attempted.
73bcce88   luigser   COMPONENTS
118
119
120
121
122
123
         */
        aborted: {
          type: Boolean,
          notify: true,
          readOnly: true,
          value: false,
eb240478   Luigi Serra   public room cards...
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
        },
  
        /**
         * Errored will be true if the browser fired an error event from the
         * XHR object (mainly network errors).
         */
        errored: {
          type: Boolean,
          notify: true,
          readOnly: true,
          value: false
        },
  
        /**
         * TimedOut will be true if the XHR threw a timeout event.
         */
        timedOut: {
          type: Boolean,
          notify: true,
          readOnly: true,
          value: false
73bcce88   luigser   COMPONENTS
145
146
147
148
        }
      },
  
      /**
eb240478   Luigi Serra   public room cards...
149
150
151
152
153
154
       * Succeeded is true if the request succeeded. The request succeeded if it
       * loaded without error, wasn't aborted, and the status code is ≥ 200, and
       * < 300, or if the status code is 0.
       *
       * The status code 0 is accepted as a success because some schemes - e.g.
       * file:// - don't provide status codes.
73bcce88   luigser   COMPONENTS
155
156
157
158
       *
       * @return {boolean}
       */
      get succeeded() {
eb240478   Luigi Serra   public room cards...
159
160
161
        if (this.errored || this.aborted || this.timedOut) {
          return false;
        }
73bcce88   luigser   COMPONENTS
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
        var status = this.xhr.status || 0;
  
        // Note: if we are using the file:// protocol, the status code will be 0
        // for all outcomes (successful or otherwise).
        return status === 0 ||
          (status >= 200 && status < 300);
      },
  
      /**
       * Sends an HTTP request to the server and returns the XHR object.
       *
       * @param {{
       *   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
180
       *   jsonPrefix: (string|undefined),
73bcce88   luigser   COMPONENTS
181
182
183
184
185
186
       *   withCredentials: (boolean|undefined)}} options -
       *     url The url to which the request is sent.
       *     method The HTTP method to use, default is GET.
       *     async By default, all requests are sent asynchronously. To send synchronous requests,
       *         set to true.
       *     body The content for the request body for POST method.
a1a3bc73   Luigi Serra   graphs updates
187
       *     headers HTTP request headers.
73bcce88   luigser   COMPONENTS
188
189
       *     handleAs The response type. Default is 'text'.
       *     withCredentials Whether or not to send credentials on the request. Default is false.
eb240478   Luigi Serra   public room cards...
190
       *   timeout: (Number|undefined)
73bcce88   luigser   COMPONENTS
191
192
193
194
195
196
197
198
199
       * @return {Promise}
       */
      send: function (options) {
        var xhr = this.xhr;
  
        if (xhr.readyState > 0) {
          return null;
        }
  
73bcce88   luigser   COMPONENTS
200
201
202
203
204
205
206
207
208
        xhr.addEventListener('progress', function (progress) {
          this._setProgress({
            lengthComputable: progress.lengthComputable,
            loaded: progress.loaded,
            total: progress.total
          });
        }.bind(this))
  
        xhr.addEventListener('error', function (error) {
eb240478   Luigi Serra   public room cards...
209
210
211
212
213
214
215
          this._setErrored(true);
          this._updateStatus();
          this.rejectCompletes(error);
        }.bind(this));
  
        xhr.addEventListener('timeout', function (error) {
          this._setTimedOut(true);
73bcce88   luigser   COMPONENTS
216
217
218
219
220
221
222
223
224
          this._updateStatus();
          this.rejectCompletes(error);
        }.bind(this));
  
        xhr.addEventListener('abort', function () {
          this._updateStatus();
          this.rejectCompletes(new Error('Request aborted.'));
        }.bind(this));
  
a1a3bc73   Luigi Serra   graphs updates
225
  
eb240478   Luigi Serra   public room cards...
226
227
228
229
230
231
232
233
234
235
236
237
238
239
        // Called after all of the above.
        xhr.addEventListener('loadend', function () {
          this._updateStatus();
  
          if (!this.succeeded) {
            this.rejectCompletes(new Error('The request failed with status code: ' + this.xhr.status));
            return;
          }
  
          this._setResponse(this.parseResponse());
          this.resolveCompletes(this);
        }.bind(this));
  
        this.url = options.url;
73bcce88   luigser   COMPONENTS
240
241
242
243
244
245
        xhr.open(
          options.method || 'GET',
          options.url,
          options.async !== false
        );
  
f748e9cf   Luigi Serra   new controllet an...
246
247
248
249
250
251
252
        var acceptType = {
          'json': 'application/json',
          'text': 'text/plain',
          'html': 'text/html',
          'xml': 'application/xml',
          'arraybuffer': 'application/octet-stream'
        }[options.handleAs];
a1a3bc73   Luigi Serra   graphs updates
253
254
255
256
257
258
259
        var headers = options.headers || Object.create(null);
        var newHeaders = Object.create(null);
        for (var key in headers) {
          newHeaders[key.toLowerCase()] = headers[key];
        }
        headers = newHeaders;
  
f748e9cf   Luigi Serra   new controllet an...
260
261
        if (acceptType && !headers['accept']) {
          headers['accept'] = acceptType;
73bcce88   luigser   COMPONENTS
262
        }
f748e9cf   Luigi Serra   new controllet an...
263
264
265
266
267
268
269
270
271
        Object.keys(headers).forEach(function (requestHeader) {
          if (/[A-Z]/.test(requestHeader)) {
            console.error('Headers must be lower case, got', requestHeader);
          }
          xhr.setRequestHeader(
            requestHeader,
            headers[requestHeader]
          );
        }, this);
73bcce88   luigser   COMPONENTS
272
  
eb240478   Luigi Serra   public room cards...
273
        if (options.async !== false) {
a1a3bc73   Luigi Serra   graphs updates
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
          var handleAs = options.handleAs;
  
          // If a JSON prefix is present, the responseType must be 'text' or the
          // browser won’t be able to parse the response.
          if (!!options.jsonPrefix || !handleAs) {
            handleAs = 'text';
          }
  
          // In IE, `xhr.responseType` is an empty string when the response
          // returns. Hence, caching it as `xhr._responseType`.
          xhr.responseType = xhr._responseType = handleAs;
  
          // Cache the JSON prefix, if it exists.
          if (!!options.jsonPrefix) {
            xhr._jsonPrefix = options.jsonPrefix;
          }
eb240478   Luigi Serra   public room cards...
290
        }
a1a3bc73   Luigi Serra   graphs updates
291
  
73bcce88   luigser   COMPONENTS
292
        xhr.withCredentials = !!options.withCredentials;
eb240478   Luigi Serra   public room cards...
293
        xhr.timeout = options.timeout;
73bcce88   luigser   COMPONENTS
294
  
a1a3bc73   Luigi Serra   graphs updates
295
        var body = this._encodeBodyObject(options.body, headers['content-type']);
73bcce88   luigser   COMPONENTS
296
  
e619a3b0   Luigi Serra   Controllet cross ...
297
298
299
300
        xhr.send(
          /** @type {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|
                     null|string|undefined} */
          (body));
73bcce88   luigser   COMPONENTS
301
302
303
304
305
306
307
308
309
310
311
312
313
314
  
        return this.completes;
      },
  
      /**
       * Attempts to parse the response body of the XHR. If parsing succeeds,
       * the value returned will be deserialized based on the `responseType`
       * set on the XHR.
       *
       * @return {*} The parsed response,
       * or undefined if there was an empty response or parsing failed.
       */
      parseResponse: function () {
        var xhr = this.xhr;
eb240478   Luigi Serra   public room cards...
315
        var responseType = xhr.responseType || xhr._responseType;
73bcce88   luigser   COMPONENTS
316
        var preferResponseText = !this.xhr.responseType;
a1a3bc73   Luigi Serra   graphs updates
317
        var prefixLen = (xhr._jsonPrefix && xhr._jsonPrefix.length) || 0;
73bcce88   luigser   COMPONENTS
318
319
320
321
  
        try {
          switch (responseType) {
            case 'json':
eb240478   Luigi Serra   public room cards...
322
323
324
325
              // If the xhr object doesn't have a natural `xhr.responseType`,
              // we can assume that the browser hasn't parsed the response for us,
              // and so parsing is our responsibility. Likewise if response is
              // undefined, as there's no way to encode undefined in JSON.
73bcce88   luigser   COMPONENTS
326
              if (preferResponseText || xhr.response === undefined) {
eb240478   Luigi Serra   public room cards...
327
328
329
330
                // Try to emulate the JSON section of the response body section of
                // the spec: https://xhr.spec.whatwg.org/#response-body
                // That is to say, we try to parse as JSON, but if anything goes
                // wrong return null.
73bcce88   luigser   COMPONENTS
331
                try {
a1a3bc73   Luigi Serra   graphs updates
332
                  return JSON.parse(xhr.responseText);
eb240478   Luigi Serra   public room cards...
333
334
                } catch (_) {
                  return null;
73bcce88   luigser   COMPONENTS
335
336
337
338
339
340
341
342
343
344
345
                }
              }
  
              return xhr.response;
            case 'xml':
              return xhr.responseXML;
            case 'blob':
            case 'document':
            case 'arraybuffer':
              return xhr.response;
            case 'text':
a1a3bc73   Luigi Serra   graphs updates
346
347
348
349
350
351
352
353
354
355
356
357
            default: {
              // If `prefixLen` is set, it implies the response should be parsed
              // as JSON once the prefix of length `prefixLen` is stripped from
              // it. Emulate the behavior above where null is returned on failure
              // to parse.
              if (prefixLen) {
                try {
                  return JSON.parse(xhr.responseText.substring(prefixLen));
                } catch (_) {
                  return null;
                }
              }
73bcce88   luigser   COMPONENTS
358
              return xhr.responseText;
a1a3bc73   Luigi Serra   graphs updates
359
            }
73bcce88   luigser   COMPONENTS
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
          }
        } catch (e) {
          this.rejectCompletes(new Error('Could not parse response. ' + e.message));
        }
      },
  
      /**
       * Aborts the request.
       */
      abort: function () {
        this._setAborted(true);
        this.xhr.abort();
      },
  
      /**
       * @param {*} body The given body of the request to try and encode.
       * @param {?string} contentType The given content type, to infer an encoding
       *     from.
e619a3b0   Luigi Serra   Controllet cross ...
378
       * @return {*} Either the encoded body as a string, if successful,
73bcce88   luigser   COMPONENTS
379
380
381
382
383
384
       *     or the unaltered body object if no encoding could be inferred.
       */
      _encodeBodyObject: function(body, contentType) {
        if (typeof body == 'string') {
          return body;  // Already encoded.
        }
e619a3b0   Luigi Serra   Controllet cross ...
385
        var bodyObj = /** @type {Object} */ (body);
73bcce88   luigser   COMPONENTS
386
387
        switch(contentType) {
          case('application/json'):
e619a3b0   Luigi Serra   Controllet cross ...
388
            return JSON.stringify(bodyObj);
73bcce88   luigser   COMPONENTS
389
          case('application/x-www-form-urlencoded'):
e619a3b0   Luigi Serra   Controllet cross ...
390
            return this._wwwFormUrlEncode(bodyObj);
73bcce88   luigser   COMPONENTS
391
        }
e619a3b0   Luigi Serra   Controllet cross ...
392
        return body;
73bcce88   luigser   COMPONENTS
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
      },
  
      /**
       * @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) {
          // TODO(rictic): handle array values here, in a consistent way with
          //   iron-ajax params.
          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.
        return encodeURIComponent(str.toString().replace(/\r?\n/g, '\r\n'))
            .replace(/%20/g, '+');
      },
  
      /**
       * Updates the status code and status text.
       */
      _updateStatus: function() {
        this._setStatus(this.xhr.status);
        this._setStatusText((this.xhr.statusText === undefined) ? '' : this.xhr.statusText);
      }
    });
  </script>