* A minimal polyfill of Fetch API. It only polyfills what we currently use. * * See https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch * * Notice that the "fetch" method itself is not exported as that would require * us to immediately support a much wide API. * * @param {strin
(input, init)
| 13505 | * @private Visible for testing |
| 13506 | */ |
| 13507 | function fetchPolyfill(input, init) { |
| 13508 | return new Promise(function (resolve, reject) { |
| 13509 | const xhr = createXhrRequest(init.method || 'GET', input); |
| 13510 | |
| 13511 | if (init.credentials == 'include') { |
| 13512 | xhr.withCredentials = true; |
| 13513 | } |
| 13514 | |
| 13515 | if (init.responseType in allowedFetchTypes_) { |
| 13516 | xhr.responseType = init.responseType; |
| 13517 | } |
| 13518 | |
| 13519 | if (init.headers) { |
| 13520 | for (const header of Object.keys(init.headers)) { |
| 13521 | xhr.setRequestHeader(header, init.headers[header]); |
| 13522 | } |
| 13523 | } |
| 13524 | |
| 13525 | xhr.onreadystatechange = () => { |
| 13526 | if (xhr.readyState < /* STATUS_RECEIVED */ 2) { |
| 13527 | return; |
| 13528 | } |
| 13529 | if (xhr.status < 100 || xhr.status > 599) { |
| 13530 | xhr.onreadystatechange = null; |
| 13531 | reject(new Error(`Unknown HTTP status ${xhr.status}`)); |
| 13532 | return; |
| 13533 | } |
| 13534 | |
| 13535 | // TODO(dvoytenko): This is currently simplified: we will wait for the |
| 13536 | // whole document loading to complete. This is fine for the use cases |
| 13537 | // we have now, but may need to be reimplemented later. |
| 13538 | if (xhr.readyState == /* COMPLETE */ 4) { |
| 13539 | resolve(new FetchResponse(xhr)); |
| 13540 | } |
| 13541 | }; |
| 13542 | xhr.onerror = () => { |
| 13543 | reject(new Error('Network failure')); |
| 13544 | }; |
| 13545 | xhr.onabort = () => { |
| 13546 | reject(new Error('Request aborted')); |
| 13547 | }; |
| 13548 | |
| 13549 | if (init.method == 'POST') { |
| 13550 | xhr.send(init.body); |
| 13551 | } else { |
| 13552 | xhr.send(); |
| 13553 | } |
| 13554 | }); |
| 13555 | } |
| 13556 | |
| 13557 | /** |
| 13558 | * @param {string} method |
no test coverage detected