UNPKG

@ace-fetch/graphql

Version:

Fetch Provider.

76 lines (75 loc) 3.11 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createUploadFetch = exports.uploadFetch = void 0; var parseHeaders = function (rawHeaders) { var headers = new Headers(); // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space // https://tools.ietf.org/html/rfc7230#section-3.2 var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' '); preProcessedHeaders.split(/\r?\n/).forEach(function (line) { var parts = line.split(':'); var key = parts.shift().trim(); if (key) { var value = parts.join(':').trim(); headers.append(key, value); } }); return headers; }; var uploadFetch = function (url, options) { return new Promise(function (resolve, reject) { var _a; var xhr = new XMLHttpRequest(); xhr.onload = function () { var opts = { status: xhr.status, statusText: xhr.statusText, headers: parseHeaders(xhr.getAllResponseHeaders() || ''), }; opts.url = 'responseURL' in xhr ? xhr.responseURL : opts.headers.get('X-Request-URL'); var body = 'response' in xhr ? xhr.response : xhr.responseText; resolve(new Response(body, opts)); }; xhr.onerror = function (ev) { reject(new TypeError('Network request failed', { cause: ev })); }; xhr.ontimeout = function (ev) { reject(new TypeError('Network request failed', { cause: ev })); }; xhr.open(options.method, url, true); // Has to be after `.open()`. See https://github.com/enyo/dropzone/issues/179 if (options.withCredentials && 'withCredentials' in xhr) { xhr.withCredentials = true; } var headers = options.headers || {}; // when set headers['X-Requested-With'] = null , can close default XHR header // see https://github.com/react-component/upload/issues/33 if (headers['X-Requested-With'] !== null) { xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); } Object.keys(headers).forEach(function (h) { if (headers[h] !== null) { xhr.setRequestHeader(h, headers[h]); } }); if (xhr.upload) { xhr.upload.onprogress = options.onProgress; } (_a = options.onAbortPossible) === null || _a === void 0 ? void 0 : _a.call(options, function () { xhr.abort(); }); xhr.send(options.body); }); }; exports.uploadFetch = uploadFetch; /** * custom fetch, support onUploadProgress * https://github.com/jaydenseric/apollo-upload-client/issues/88 */ var createUploadFetch = function (preferredFetch) { return function (uri, options) { if (options.onProgress) { return (0, exports.uploadFetch)(uri, options); } return (preferredFetch !== null && preferredFetch !== void 0 ? preferredFetch : fetch)(uri, options); }; }; exports.createUploadFetch = createUploadFetch;