Skip to content

Commit 3990cc1

Browse files
authored
fix: Fetch handler hacks for Mirage (#9199)
* Allow `store.request` to be intercepted by Mirage * Don't `cloneResponse` for Mirage mock responses Mirage mock responses don't properly include a body stream.
1 parent 5ed8497 commit 3990cc1

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

packages/request/src/fetch.ts

+20-5
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,17 @@
1111
* @module @ember-data/request/fetch
1212
* @main @ember-data/request/fetch
1313
*/
14+
import { getOwnConfig, macroCondition } from '@embroider/macros';
15+
1416
import { cloneResponseProperties, type Context } from './-private/context';
1517
import type { HttpErrorProps } from './-private/utils';
1618

19+
// Lazily close over fetch to avoid breaking Mirage
1720
const _fetch: typeof fetch =
1821
typeof fetch !== 'undefined'
19-
? fetch
22+
? (...args) => fetch(...args)
2023
: typeof FastBoot !== 'undefined'
21-
? (FastBoot.require('node-fetch') as typeof fetch)
24+
? (...args) => (FastBoot.require('node-fetch') as typeof fetch)(...args)
2225
: ((() => {
2326
throw new Error('No Fetch Implementation Found');
2427
}) as typeof fetch);
@@ -30,6 +33,12 @@ function cloneResponse(response: Response, overrides: Partial<Response>) {
3033
return new Response(response.body, Object.assign(props, overrides));
3134
}
3235

36+
let IS_MAYBE_MIRAGE = () => false;
37+
if (macroCondition(getOwnConfig<{ env: { TESTING: boolean } }>().env.TESTING)) {
38+
IS_MAYBE_MIRAGE = () =>
39+
Boolean(typeof window !== 'undefined' && (window as { server?: { pretender: unknown } }).server?.pretender);
40+
}
41+
3342
const MUTATION_OPS = new Set(['updateRecord', 'createRecord', 'deleteRecord']);
3443
const ERROR_STATUS_CODE_FOR = new Map([
3544
[400, 'Bad Request'],
@@ -115,9 +124,15 @@ const Fetch = {
115124
const isMutationOp = Boolean(op && MUTATION_OPS.has(op));
116125

117126
if (!isError && !isMutationOp && response.status !== 204 && !response.headers.has('date')) {
118-
const headers = new Headers(response.headers);
119-
headers.set('date', new Date().toUTCString());
120-
response = cloneResponse(response, { headers });
127+
if (IS_MAYBE_MIRAGE()) {
128+
response.headers.set('date', new Date().toUTCString());
129+
} else {
130+
const headers = new Headers(response.headers);
131+
headers.set('date', new Date().toUTCString());
132+
response = cloneResponse(response, {
133+
headers,
134+
});
135+
}
121136
}
122137

123138
context.setResponse(response);

0 commit comments

Comments
 (0)