forked from wheresrhys/fetch-mock
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch-handler.js
executable file
·309 lines (275 loc) · 8.54 KB
/
fetch-handler.js
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
const { debug, setDebugPhase, getDebug } = require('./debug');
const responseBuilder = require('./response-builder');
const requestUtils = require('./request-utils');
const FetchMock = {};
// see https://heycam.github.io/webidl/#aborterror for the standardised interface
// Note that this differs slightly from node-fetch
class AbortError extends Error {
constructor() {
super(...arguments);
this.name = 'AbortError';
this.message = 'The operation was aborted.';
// Do not include this class in the stacktrace
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
}
// Patch native fetch to avoid "NotSupportedError:ReadableStream uploading is not supported" in Safari.
// See also https://github.com/wheresrhys/fetch-mock/issues/584
// See also https://stackoverflow.com/a/50952018/1273406
const patchNativeFetchForSafari = (nativeFetch) => {
// Try to patch fetch only on Safari
if (
typeof navigator === 'undefined' ||
!navigator.vendor ||
navigator.vendor !== 'Apple Computer, Inc.'
) {
return nativeFetch;
}
// It seems the code is working on Safari thus patch native fetch to avoid the error.
return async (request) => {
const { method } = request;
if (!['POST', 'PUT', 'PATCH'].includes(method)) {
// No patch is required in this case
return nativeFetch(request);
}
const body = await request.clone().text();
const {
cache,
credentials,
headers,
integrity,
mode,
redirect,
referrer,
} = request;
const init = {
body,
cache,
credentials,
headers,
integrity,
mode,
redirect,
referrer,
method,
};
return nativeFetch(request.url, init);
};
};
const resolve = async (
{ response, responseIsFetch = false },
url,
options,
request
) => {
const debug = getDebug('resolve()');
debug('Recursively resolving function and promise responses');
// We want to allow things like
// - function returning a Promise for a response
// - delaying (using a timeout Promise) a function's execution to generate
// a response
// Because of this we can't safely check for function before Promisey-ness,
// or vice versa. So to keep it DRY, and flexible, we keep trying until we
// have something that looks like neither Promise nor function
while (true) {
if (typeof response === 'function') {
debug(' Response is a function');
// in the case of falling back to the network we need to make sure we're using
// the original Request instance, not our normalised url + options
if (responseIsFetch) {
if (request) {
debug(' -> Calling fetch with Request instance');
return response(request);
}
debug(' -> Calling fetch with url and options');
return response(url, options);
} else {
debug(' -> Calling response function');
response = response(url, options, request);
}
} else if (typeof response.then === 'function') {
debug(' Response is a promise');
debug(' -> Resolving promise');
response = await response;
} else {
debug(' Response is not a function or a promise');
debug(' -> Exiting response resolution recursion');
return response;
}
}
};
FetchMock.needsAsyncBodyExtraction = function ({ request }) {
return request && this.routes.some(({ usesBody }) => usesBody);
};
FetchMock.fetchHandler = function (url, options) {
setDebugPhase('handle');
const debug = getDebug('fetchHandler()');
debug('fetch called with:', url, options);
const normalizedRequest = requestUtils.normalizeRequest(
url,
options,
this.config.Request
);
debug('Request normalised');
debug(' url', normalizedRequest.url);
debug(' options', normalizedRequest.options);
debug(' request', normalizedRequest.request);
debug(' signal', normalizedRequest.signal);
if (this.needsAsyncBodyExtraction(normalizedRequest)) {
debug(
'Need to wait for Body to be streamed before calling router: switching to async mode'
);
return this._extractBodyThenHandle(normalizedRequest);
}
return this._fetchHandler(normalizedRequest);
};
FetchMock._extractBodyThenHandle = async function (normalizedRequest) {
normalizedRequest.options.body = await normalizedRequest.options.body;
return this._fetchHandler(normalizedRequest);
};
FetchMock._fetchHandler = function ({ url, options, request, signal }) {
const { route, callLog } = this.executeRouter(url, options, request);
this.recordCall(callLog);
// this is used to power the .flush() method
let done;
this._holdingPromises.push(new this.config.Promise((res) => (done = res)));
// wrapped in this promise to make sure we respect custom Promise
// constructors defined by the user
return new this.config.Promise((res, rej) => {
if (signal) {
debug('signal exists - enabling fetch abort');
const abort = () => {
debug('aborting fetch');
// note that DOMException is not available in node.js;
// even node-fetch uses a custom error class:
// https://github.com/bitinn/node-fetch/blob/master/src/abort-error.js
rej(
typeof DOMException !== 'undefined'
? new DOMException('The operation was aborted.', 'AbortError')
: new AbortError()
);
done();
};
if (signal.aborted) {
debug('signal is already aborted - aborting the fetch');
abort();
}
signal.addEventListener('abort', abort);
}
this.generateResponse({ route, url, options, request, callLog })
.then(res, rej)
.then(done, done)
.then(() => {
setDebugPhase();
});
});
};
FetchMock.fetchHandler.isMock = true;
FetchMock.executeRouter = function (url, options, request) {
const debug = getDebug('executeRouter()');
const callLog = { url, options, request, isUnmatched: true };
debug(`Attempting to match request to a route`);
if (this.getOption('fallbackToNetwork') === 'always') {
debug(
' Configured with fallbackToNetwork=always - passing through to fetch'
);
return {
route: { response: this.getNativeFetch(), responseIsFetch: true },
// BUG - this callLog never used to get sent. Discovered the bug
// but can't fix outside a major release as it will potentially
// cause too much disruption
//
// callLog,
};
}
const route = this.router(url, options, request);
if (route) {
debug(' Matching route found');
return {
route,
callLog: {
url,
options,
request,
identifier: route.identifier,
},
};
}
if (this.getOption('warnOnFallback')) {
console.warn(`Unmatched ${(options && options.method) || 'GET'} to ${url}`); // eslint-disable-line
}
if (this.fallbackResponse) {
debug(' No matching route found - using fallbackResponse');
return { route: { response: this.fallbackResponse }, callLog };
}
if (!this.getOption('fallbackToNetwork')) {
throw new Error(
`fetch-mock: No fallback response defined for ${
(options && options.method) || 'GET'
} to ${url}`
);
}
debug(' Configured to fallbackToNetwork - passing through to fetch');
return {
route: { response: this.getNativeFetch(), responseIsFetch: true },
callLog,
};
};
FetchMock.generateResponse = async function ({
route,
url,
options,
request,
callLog = {},
}) {
const debug = getDebug('generateResponse()');
const response = await resolve(route, url, options, request);
// If the response says to throw an error, throw it
// Type checking is to deal with sinon spies having a throws property :-0
if (response.throws && typeof response !== 'function') {
debug('response.throws is defined - throwing an error');
throw response.throws;
}
// If the response is a pre-made Response, respond with it
if (this.config.Response.prototype.isPrototypeOf(response)) {
debug('response is already a Response instance - returning it');
callLog.response = response;
return response;
}
// finally, if we need to convert config into a response, we do it
const [realResponse, finalResponse] = responseBuilder({
url,
responseConfig: response,
fetchMock: this,
route,
});
callLog.response = realResponse;
return finalResponse;
};
FetchMock.router = function (url, options, request) {
const route = this.routes.find((route, i) => {
debug(`Trying to match route ${i}`);
return route.matcher(url, options, request);
});
if (route) {
return route;
}
};
FetchMock.getNativeFetch = function () {
const func = this.realFetch || (this.isSandbox && this.config.fetch);
if (!func) {
throw new Error(
'fetch-mock: Falling back to network only available on global fetch-mock, or by setting config.fetch on sandboxed fetch-mock'
);
}
return patchNativeFetchForSafari(func);
};
FetchMock.recordCall = function (obj) {
debug('Recording fetch call', obj);
if (obj) {
this._calls.push(obj);
}
};
module.exports = FetchMock;