summaryrefslogtreecommitdiff
path: root/chromium/chrome/browser/resources/cryptotoken/textfetcher.js
blob: 471aa22d9b791b22bef37c7c836e86585575dd65 (plain)
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 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Implements a simple XmlHttpRequest-based text document
 * fetcher.
 *
 */
'use strict';

/**
 * A fetcher of text files.
 * @interface
 */
function TextFetcher() {}

/**
 * @param {string} url The URL to fetch.
 * @param {string?} opt_method The HTTP method to use (default GET)
 * @param {string?} opt_body The request body
 * @return {!Promise<string>} A promise for the fetched text. In case of an
 *     error, this promise is rejected with an HTTP status code.
 */
TextFetcher.prototype.fetch = function(url, opt_method, opt_body) {};

/**
 * @constructor
 * @implements {TextFetcher}
 */
function XhrTextFetcher() {}

/**
 * @param {string} url The URL to fetch.
 * @param {string?} opt_method The HTTP method to use (default GET)
 * @param {string?} opt_body The request body
 * @return {!Promise<string>} A promise for the fetched text. In case of an
 *     error, this promise is rejected with an HTTP status code.
 */
XhrTextFetcher.prototype.fetch = function(url, opt_method, opt_body) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest();
    var method = opt_method || 'GET';
    xhr.open(method, url, true);
    xhr.onloadend = function() {
      if (xhr.status != 200) {
        reject(xhr.status);
        return;
      }
      resolve(xhr.responseText);
    };
    xhr.onerror = function() {
      // Treat any network-level errors as though the page didn't exist.
      reject(404);
    };
    if (opt_body) {
      xhr.send(opt_body);
    } else {
      xhr.send();
    }
  });
};