MCPcopy Index your code
hub / github.com/ampproject/amphtml / fetchPolyfill

Function fetchPolyfill

src/polyfills/fetch.js:37–86  ·  view source on GitHub ↗
(input, init = {})

Source from the content-addressed store, hash-verified

35 * @return {!Promise<!FetchResponse>}
36 */
37export function fetchPolyfill(input, init = {}) {
38 return new Promise(function (resolve, reject) {
39 const requestMethod = normalizeMethod(init.method || 'GET');
40 const xhr = createXhrRequest(requestMethod, input);
41
42 if (init.credentials == 'include') {
43 xhr.withCredentials = true;
44 }
45
46 if (init.responseType === 'document' || init.responseType === 'text') {
47 xhr.responseType = init.responseType;
48 }
49
50 if (init.headers) {
51 Object.keys(init.headers).forEach(function (header) {
52 xhr.setRequestHeader(header, init.headers[header]);
53 });
54 }
55
56 xhr.onreadystatechange = () => {
57 if (xhr.readyState < /* STATUS_RECEIVED */ 2) {
58 return;
59 }
60 if (xhr.status < 100 || xhr.status > 599) {
61 xhr.onreadystatechange = null;
62 reject(user().createExpectedError(`Unknown HTTP status ${xhr.status}`));
63 return;
64 }
65
66 // TODO(dvoytenko): This is currently simplified: we will wait for the
67 // whole document loading to complete. This is fine for the use cases
68 // we have now, but may need to be reimplemented later.
69 if (xhr.readyState == /* COMPLETE */ 4) {
70 resolve(new FetchResponse(xhr));
71 }
72 };
73 xhr.onerror = () => {
74 reject(user().createExpectedError('Network failure'));
75 };
76 xhr.onabort = () => {
77 reject(user().createExpectedError('Request aborted'));
78 };
79
80 if (requestMethod == 'POST') {
81 xhr.send(init.body);
82 } else {
83 xhr.send();
84 }
85 });
86}
87
88/**
89 * @param {string} method

Callers 1

Calls 7

userFunction · 0.90
normalizeMethodFunction · 0.85
createXhrRequestFunction · 0.70
resolveFunction · 0.50
forEachMethod · 0.45
createExpectedErrorMethod · 0.45
sendMethod · 0.45

Tested by

no test coverage detected