UNPKG

5 kBJavaScriptView Raw
1import { polyfillNeeded } from './utils.js';
2/**
3 * Note: the "fetch.Request" default value is available for fetch imported from
4 * the "node-fetch" package and not in browsers. This is OK since browsers
5 * will be importing umd-polyfill.js from that path "self" is passed the
6 * decorator so the default value will not be used (because browsers that define
7 * fetch also has Request). One quirky setup where self.fetch exists but
8 * self.Request does not is when the "unfetch" minimal fetch polyfill is used
9 * on top of IE11; for this case the browser will try to use the fetch.Request
10 * default value which in turn will be undefined but then then "if (Request)"
11 * will ensure that you get a patched fetch but still no Request (as expected).
12 * @param {fetch, Request = fetch.Request}
13 * @returns {fetch: abortableFetch, Request: AbortableRequest}
14 */
15export default function abortableFetchDecorator(patchTargets) {
16 if ('function' === typeof patchTargets) {
17 patchTargets = { fetch: patchTargets };
18 }
19 const {
20 fetch,
21 Request: NativeRequest = fetch.Request,
22 AbortController: NativeAbortController,
23 __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL = false,
24 } = patchTargets;
25
26 if (
27 !polyfillNeeded({
28 fetch,
29 Request: NativeRequest,
30 AbortController: NativeAbortController,
31 __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL,
32 })
33 ) {
34 return { fetch, Request };
35 }
36
37 let Request = NativeRequest;
38 // Note that the "unfetch" minimal fetch polyfill defines fetch() without
39 // defining window.Request, and this polyfill need to work on top of unfetch
40 // hence we only patch it if it's available. Also we don't patch it if signal
41 // is already available on the Request prototype because in this case support
42 // is present and the patching below can cause a crash since it assigns to
43 // request.signal which is technically a read-only property. This latter error
44 // happens when you run the main5.js node-fetch example in the repo
45 // "abortcontroller-polyfill-examples". The exact error is:
46 // request.signal = init.signal;
47 // ^
48 // TypeError: Cannot set property signal of #<Request> which has only a getter
49 if ((Request && !Request.prototype.hasOwnProperty('signal')) || __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL) {
50 Request = function Request(input, init) {
51 let signal;
52 if (init && init.signal) {
53 signal = init.signal;
54 // Never pass init.signal to the native Request implementation when the polyfill has
55 // been installed because if we're running on top of a browser with a
56 // working native AbortController (i.e. the polyfill was installed due to
57 // __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL being set), then passing our
58 // fake AbortSignal to the native fetch will trigger:
59 // TypeError: Failed to construct 'Request': member signal is not of type AbortSignal.
60 delete init.signal;
61 }
62 const request = new NativeRequest(input, init);
63 if (signal) {
64 Object.defineProperty(request, 'signal', {
65 writable: false,
66 enumerable: false,
67 configurable: true,
68 value: signal,
69 });
70 }
71 return request;
72 };
73 Request.prototype = NativeRequest.prototype;
74 }
75
76 const realFetch = fetch;
77 const abortableFetch = (input, init) => {
78 const signal = Request && Request.prototype.isPrototypeOf(input) ? input.signal : init ? init.signal : undefined;
79
80 if (signal) {
81 let abortError;
82 try {
83 abortError = new DOMException('Aborted', 'AbortError');
84 } catch (err) {
85 // IE 11 does not support calling the DOMException constructor, use a
86 // regular error object on it instead.
87 abortError = new Error('Aborted');
88 abortError.name = 'AbortError';
89 }
90
91 // Return early if already aborted, thus avoiding making an HTTP request
92 if (signal.aborted) {
93 return Promise.reject(abortError);
94 }
95
96 // Turn an event into a promise, reject it once `abort` is dispatched
97 const cancellation = new Promise((_, reject) => {
98 signal.addEventListener('abort', () => reject(abortError), { once: true });
99 });
100
101 if (init && init.signal) {
102 // Never pass .signal to the native implementation when the polyfill has
103 // been installed because if we're running on top of a browser with a
104 // working native AbortController (i.e. the polyfill was installed due to
105 // __FORCE_INSTALL_ABORTCONTROLLER_POLYFILL being set), then passing our
106 // fake AbortSignal to the native fetch will trigger:
107 // TypeError: Failed to execute 'fetch' on 'Window': member signal is not of type AbortSignal.
108 delete init.signal;
109 }
110 // Return the fastest promise (don't need to wait for request to finish)
111 return Promise.race([cancellation, realFetch(input, init)]);
112 }
113
114 return realFetch(input, init);
115 };
116
117 return { fetch: abortableFetch, Request };
118}