@@ -34,6 +34,12 @@ interface RequestMethod<P extends Payload> {
34
34
}
35
35
36
36
interface RequiredOptions < P extends Payload > extends RequestInit {
37
+ /**
38
+ * Base of the request URL, default to `location.origin` if available.
39
+ * Provide a valid url if you want to use relative `resource` path
40
+ * when module loaded in `file://`, `about:blank` or Node.js environment.
41
+ */
42
+ base ?: string
37
43
/**
38
44
* Part of the request URL
39
45
*/
@@ -124,6 +130,10 @@ const CONTENT_TYPES = {
124
130
} as const
125
131
126
132
const DEFAULTS : RequiredOptions < Payload > = {
133
+ base :
134
+ typeof location !== 'undefined' && location . origin !== 'null'
135
+ ? location . origin
136
+ : undefined ,
127
137
highWaterMark : 1024 * 1024 * 10 , // 10mb
128
138
onRequest : ( ) => { } ,
129
139
onResponse ( result ) {
@@ -208,20 +218,17 @@ function request<P extends Payload>(
208
218
baseOptions : Options < P >
209
219
) : ResponsePromise < P > {
210
220
const options : RequestOptions < P > = mergeOptions ( DEFAULTS , baseOptions )
211
- const promise = new Promise < Response < P > > ( ( resolve , reject ) => {
212
- const url = new URL (
213
- options . resource ,
214
- typeof location === 'undefined' ? undefined : location . origin
215
- )
216
221
222
+ let timerID : ReturnType < typeof setTimeout >
223
+ const promise = new Promise < Response < P > > ( ( resolve , reject ) => {
224
+ const url = new URL ( options . resource , options . base )
217
225
url . search += options . params
218
226
219
227
if ( options . json != null ) {
220
228
options . body = JSON . stringify ( options . json )
221
229
options . headers . set ( 'content-type' , CONTENT_TYPES . json )
222
230
}
223
231
224
- let timerID : ReturnType < typeof setTimeout >
225
232
if ( options . timeout ! > 0 ) {
226
233
const controller = new AbortController ( )
227
234
@@ -240,14 +247,11 @@ function request<P extends Payload>(
240
247
options . signal = controller . signal
241
248
}
242
249
243
- // Running fetch in next tick allow us to set headers after creating promise
244
- setTimeout ( ( ) =>
245
- Promise . resolve ( options . onRequest ( url , options ) )
246
- . then ( ( ) => fetch ( url , options ) )
247
- . then ( ( response ) => Object . assign ( response , { options } ) )
248
- . then ( resolve , reject )
249
- . then ( ( ) => clearTimeout ( timerID ) )
250
- )
250
+ Promise . resolve ( options . onRequest ( url , options ) )
251
+ . then ( ( ) => fetch ( url , options ) )
252
+ . then ( ( response ) => Object . assign ( response , { options } ) )
253
+ . then ( resolve , reject )
254
+ . then ( ( ) => clearTimeout ( timerID ) )
251
255
} )
252
256
. then ( options . onResponse )
253
257
. then ( options . onSuccess , options . onFailure ) as ResponsePromise < P >
0 commit comments