Skip to content

Commit d977397

Browse files
authored
Port 4.12 fetch updates to canary (#9203)
1 parent c4d76ed commit d977397

File tree

1 file changed

+21
-7
lines changed

1 file changed

+21
-7
lines changed

packages/request/src/fetch.ts

+21-7
Original file line numberDiff line numberDiff line change
@@ -11,15 +11,17 @@
1111
* @module @ember-data/request/fetch
1212
* @main @ember-data/request/fetch
1313
*/
14-
import type { HttpErrorProps } from '-private/utils';
14+
import { getOwnConfig, macroCondition } from '@embroider/macros';
1515

1616
import { cloneResponseProperties, type Context } from './-private/context';
17+
import type { HttpErrorProps } from './-private/utils';
1718

19+
// Lazily close over fetch to avoid breaking Mirage
1820
const _fetch: typeof fetch =
1921
typeof fetch !== 'undefined'
20-
? fetch
22+
? (...args) => fetch(...args)
2123
: typeof FastBoot !== 'undefined'
22-
? (FastBoot.require('node-fetch') as typeof fetch)
24+
? (...args) => (FastBoot.require('node-fetch') as typeof fetch)(...args)
2325
: ((() => {
2426
throw new Error('No Fetch Implementation Found');
2527
}) as typeof fetch);
@@ -31,6 +33,12 @@ function cloneResponse(response: Response, overrides: Partial<Response>) {
3133
return new Response(response.body, Object.assign(props, overrides));
3234
}
3335

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+
3442
const MUTATION_OPS = new Set(['updateRecord', 'createRecord', 'deleteRecord']);
3543
const ERROR_STATUS_CODE_FOR = new Map([
3644
[400, 'Bad Request'],
@@ -94,7 +102,7 @@ const ERROR_STATUS_CODE_FOR = new Map([
94102
*/
95103
const Fetch = {
96104
async request(context: Context) {
97-
let response;
105+
let response: Response;
98106

99107
try {
100108
response = await _fetch(context.request.url!, context.request);
@@ -116,9 +124,15 @@ const Fetch = {
116124
const isMutationOp = Boolean(op && MUTATION_OPS.has(op));
117125

118126
if (!isError && !isMutationOp && response.status !== 204 && !response.headers.has('date')) {
119-
const headers = new Headers(response.headers);
120-
headers.set('date', new Date().toUTCString());
121-
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+
}
122136
}
123137

124138
context.setResponse(response);

0 commit comments

Comments
 (0)