11
11
* @module @ember -data/request/fetch
12
12
* @main @ember -data/request/fetch
13
13
*/
14
- import type { HttpErrorProps } from '-private/utils ' ;
14
+ import { getOwnConfig , macroCondition } from '@embroider/macros ' ;
15
15
16
16
import { cloneResponseProperties , type Context } from './-private/context' ;
17
+ import type { HttpErrorProps } from './-private/utils' ;
17
18
19
+ // Lazily close over fetch to avoid breaking Mirage
18
20
const _fetch : typeof fetch =
19
21
typeof fetch !== 'undefined'
20
- ? fetch
22
+ ? ( ... args ) => fetch ( ... args )
21
23
: typeof FastBoot !== 'undefined'
22
- ? ( FastBoot . require ( 'node-fetch' ) as typeof fetch )
24
+ ? ( ... args ) => ( FastBoot . require ( 'node-fetch' ) as typeof fetch ) ( ... args )
23
25
: ( ( ( ) => {
24
26
throw new Error ( 'No Fetch Implementation Found' ) ;
25
27
} ) as typeof fetch ) ;
@@ -31,6 +33,12 @@ function cloneResponse(response: Response, overrides: Partial<Response>) {
31
33
return new Response ( response . body , Object . assign ( props , overrides ) ) ;
32
34
}
33
35
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
+
34
42
const MUTATION_OPS = new Set ( [ 'updateRecord' , 'createRecord' , 'deleteRecord' ] ) ;
35
43
const ERROR_STATUS_CODE_FOR = new Map ( [
36
44
[ 400 , 'Bad Request' ] ,
@@ -94,7 +102,7 @@ const ERROR_STATUS_CODE_FOR = new Map([
94
102
*/
95
103
const Fetch = {
96
104
async request ( context : Context ) {
97
- let response ;
105
+ let response : Response ;
98
106
99
107
try {
100
108
response = await _fetch ( context . request . url ! , context . request ) ;
@@ -116,9 +124,15 @@ const Fetch = {
116
124
const isMutationOp = Boolean ( op && MUTATION_OPS . has ( op ) ) ;
117
125
118
126
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
+ }
122
136
}
123
137
124
138
context . setResponse ( response ) ;
0 commit comments