/
types.ts
771 lines (746 loc) · 23.6 KB
/
types.ts
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
/**
* The Wretch object used to perform easy fetch requests.
*
* ```ts
* import wretch from "wretch"
*
* // Reusable wretch instance
* const w = wretch("https://domain.com", { mode: "cors" })
* ```
*
* Immutability : almost every method of this class return a fresh Wretch object.
*/
export interface Wretch<Self = unknown, Chain = unknown, Resolver = undefined> {
/**
* @private @internal
*/
_url: string,
/**
* @private @internal
*/
_options: WretchOptions,
/**
* @private @internal
*/
_config: Config,
/**
* @private @internal
*/
_catchers: Map<number | string | symbol, (error: WretchError, originalRequest: Wretch<Self, Chain, Resolver>) => void>
/**
* @private @internal
*/
_resolvers: ((resolver: Resolver extends undefined ? Chain & WretchResponseChain<Self, Chain> : Resolver, originalRequest: Wretch<Self, Chain, Resolver>) => any)[]
/**
* @private @internal
*/
_deferred: WretchDeferredCallback<Self, Chain, Resolver>[]
/**
* @private @internal
*/
_middlewares: ConfiguredMiddleware[]
/**
* @private @internal
*/
_addons: WretchAddon<unknown, Chain>[]
/**
* Register an Addon to enhance the wretch or response objects.
*
* ```js
* import FormDataAddon from "wretch/addons/formData"
* import QueryStringAddon from "wretch/addons/queryString"
*
* // Add both addons
* const w = wretch().addon(FormDataAddon).addon(QueryStringAddon)
*
* // Additional features are now available
* w.formData({ hello: "world" }).query({ check: true })
* ```
*
* @category Helpers
* @param addon - A Wretch addon to register
*/
addon<W, R>(addon: WretchAddon<W, R>): W & Self & Wretch<Self & W, Chain & R, Resolver>
/**
* Sets the method (text, json ...) used to parse the data contained in the
* response body in case of an HTTP error is returned.
*
* _Note: if the response Content-Type header is set to "application/json", the body will be parsed as json regardless of the errorType._
*
* ```js
* wretch("http://server/which/returns/an/error/with/a/json/body")
* .errorType("json")
* .get()
* .res()
* .catch(error => {
* // error[errorType] (here, json) contains the parsed body
* console.log(error.json)
* })
* ```
*
* @category Helpers
* @param method - The method to call on the Fetch response to read the body and use it as the Error message
*/
errorType(this: Self & Wretch<Self, Chain, Resolver>, method: string): this
/**
* Sets non-global polyfills - for instance in browserless environments.
*
* Needed for libraries like [fetch-ponyfill](https://github.com/qubyte/fetch-ponyfill).
*
* ```javascript
* const fetch = require("node-fetch");
* const FormData = require("form-data");
*
* wretch("http://domain.com")
* .polyfills({
* fetch: fetch,
* FormData: FormData,
* URLSearchParams: require("url").URLSearchParams,
* })
* .get()
* ```
*
* @category Helpers
* @param polyfills - An object containing the polyfills
* @param replace - If true, replaces the current polyfills instead of mixing in
*/
polyfills(this: Self & Wretch<Self, Chain, Resolver>, polyfills: Partial<Config["polyfills"]>, replace?: boolean): this
/**
* Appends or replaces the url.
*
* ```js
* wretch("/root").url("/sub").get().json();
*
* // Can be used to set a base url
*
* // Subsequent requests made using the 'blogs' object will be prefixed with "http://domain.com/api/blogs"
* const blogs = wretch("http://domain.com/api/blogs");
*
* // Perfect for CRUD apis
* const id = await blogs.post({ name: "my blog" }).json(blog => blog.id);
* const blog = await blogs.get(`/${id}`).json();
* console.log(blog.name);
*
* await blogs.url(`/${id}`).delete().res();
*
* // And to replace the base url if needed :
* const noMoreBlogs = blogs.url("http://domain2.com/", true);
* ```
*
* @category Helpers
* @param url - Url segment
* @param replace - If true, replaces the current url instead of appending
*/
url(this: Self & Wretch<Self, Chain, Resolver>, url: string, replace?: boolean): this
/**
* Sets the fetch options.
*
* ```js
* wretch("...").options({ credentials: "same-origin" });
* ```
*
* Wretch being immutable, you can store the object for later use.
*
* ```js
* const corsWretch = wretch().options({ credentials: "include", mode: "cors" });
*
* corsWretch.get("http://endpoint1");
* corsWretch.get("http://endpoint2");
* ```
*
* You can override instead of mixing in the existing options by passing a boolean
* flag.
*
* ```js
* // By default options are mixed in :
* let w = wretch()
* .options({ headers: { "Accept": "application/json" } })
* .options({ encoding: "same-origin", headers: { "X-Custom": "Header" } });
* console.log(JSON.stringify(w._options))
* // => {"encoding":"same-origin", "headers":{"Accept":"application/json","X-Custom":"Header"}}
*
* // With the flag, options are overridden :
* w = wretch()
* .options({ headers: { "Accept": "application/json" } })
* .options(
* { encoding: "same-origin", headers: { "X-Custom": "Header" } },
* true,
* );
* console.log(JSON.stringify(w._options))
* // => {"encoding":"same-origin","headers":{"X-Custom":"Header"}}
* ```
*
* @category Helpers
* @param options - New options
* @param replace - If true, replaces the existing options
*/
options(this: Self & Wretch<Self, Chain, Resolver>, options: WretchOptions, replace?: boolean): this
/**
* Sets the request headers.
*
* ```js
* wretch("...")
* .headers({ "Content-Type": "text/plain", Accept: "application/json" })
* .post("my text")
* .json();
* ```
*
* @category Helpers
* @param headerValues - An object containing header keys and values
*/
headers(this: Self & Wretch<Self, Chain, Resolver>, headerValues: HeadersInit): this
/**
* Shortcut to set the "Accept" header.
*
* ```js
* wretch("...").accept("application/json");
* ```
*
* @category Helpers
* @param headerValue - Header value
*/
accept(this: Self & Wretch<Self, Chain, Resolver>, headerValue: string): this
/**
* Shortcut to set the "Content-Type" header.
*
* ```js
* wretch("...").content("application/json");
* ```
*
* @category Helpers
* @param headerValue - Header value
*/
content(this: Self & Wretch<Self, Chain, Resolver>, headerValue: string): this
/**
* Shortcut to set the "Authorization" header.
*
* ```js
* wretch("...").auth("Basic d3JldGNoOnJvY2tz");
* ```
*
* @category Helpers
* @param headerValue - Header value
*/
auth(this: Self & Wretch<Self, Chain, Resolver>, headerValue: string): this
/**
* Adds a [catcher](https://github.com/elbywan/wretch#catchers) which will be
* called on every subsequent request error.
*
* Very useful when you need to perform a repetitive action on a specific error
* code.
*
* ```js
* const w = wretch()
* .catcher(404, err => redirect("/routes/notfound", err.message))
* .catcher(500, err => flashMessage("internal.server.error"))
*
* // No need to catch the 404 or 500 codes, they are already taken care of.
* w.get("http://myapi.com/get/something").json()
*
* // Default catchers can be overridden if needed.
* w
* .get("http://myapi.com/get/something")
* .notFound(err =>
* // overrides the default 'redirect' catcher
* )
* .json()
* ```
*
* The original request is passed along the error and can be used in order to
* perform an additional request.
*
* ```js
* const reAuthOn401 = wretch()
* .catcher(401, async (error, request) => {
* // Renew credentials
* const token = await wretch("/renewtoken").get().text();
* storeToken(token);
* // Replay the original request with new credentials
* return request.auth(token).fetch().unauthorized((err) => {
* throw err;
* }).json();
* });
*
* reAuthOn401
* .get("/resource")
* .json() // <- Will only be called for the original promise
* .then(callback); // <- Will be called for the original OR the replayed promise result
* ```
*
* @category Helpers
* @param errorId - Error code or name
* @param catcher - The catcher method
*/
catcher(this: Self & Wretch<Self, Chain, Resolver>, errorId: number | string, catcher: (error: WretchError, originalRequest: this) => any): this
/**
* Defer one or multiple request chain methods that will get called just before the request is sent.
*
* ```js
* // Small fictional example: deferred authentication
*
* // If you cannot retrieve the auth token while configuring the wretch object you can use .defer to postpone the call
* const api = wretch("http://some-domain.com").defer((w, url, options) => {
* // If we are hitting the route /user…
* if (/\/user/.test(url)) {
* const { token } = options.context;
* return w.auth(token);
* }
* return w;
* });
*
* // ... //
*
* const token = await getToken(request.session.user);
*
* // .auth gets called here automatically
* api.options({
* context: { token },
* }).get("/user/1").res();
* ```
*
* @category Helpers
* @param callback - Exposes the wretch instance, url and options to program deferred methods.
* @param clear - Replace the existing deferred methods if true instead of pushing to the existing list.
*/
defer<Clear extends boolean = false>(
this: Self & Wretch<Self, Chain, Resolver>,
callback: WretchDeferredCallback<Self, Chain, Resolver>,
clear?: Clear
): this
/**
* Programs a resolver to perform response chain tasks automatically.
*
* Very useful when you need to perform repetitive actions on the wretch response.
*
* _The clear argument, if set to true, removes previously defined resolvers._
*
* ```js
* // Program "response" chain actions early on
* const w = wretch()
* .addon(PerfsAddon())
* .resolve(resolver => resolver
* // monitor every request…
* .perfs(console.log)
* // automatically parse and return json…
* .json()
* )
*
* const myJson = await w.url("http://a.com").get()
* // Equivalent to:
* // w.url("http://a.com")
* // .get()
* // <- the resolver chain is automatically injected here !
* // .perfs(console.log)
* // .json()
* ```
*
* @category Helpers
* @param resolver - Resolver callback
*/
resolve<ResolverReturn, Clear extends boolean = false>(
this: Self & Wretch<Self, Chain, Resolver>,
resolver: (
chain:
Resolver extends undefined ?
Chain & WretchResponseChain<Self, Chain, undefined> :
Clear extends true ?
Chain & WretchResponseChain<Self, Chain, undefined> :
Resolver,
originalRequest: Self & Wretch<Self, Chain, Clear extends true ? undefined : Resolver>
) => ResolverReturn,
clear?: Clear
): Self & Wretch<Self, Chain, ResolverReturn>
/**
* Add middlewares to intercept a request before being sent.
*
* ```javascript
* // A simple delay middleware.
* const delayMiddleware = delay => next => (url, opts) => {
* return new Promise(res => setTimeout(() => res(next(url, opts)), delay))
* }
*
* // The request will be delayed by 1 second.
* wretch("...").middlewares([
* delayMiddleware(1000)
* ]).get().res()
* ```
*
* @category Helpers
*/
middlewares(this: Self & Wretch<Self, Chain, Resolver>, middlewares: ConfiguredMiddleware[], clear?: boolean): this
/**
* Sets the request body with any content.
*
* ```js
* wretch("...").body("hello").put();
* // Note that calling put/post methods with a non-object argument is equivalent:
* wretch("...").put("hello");
* ```
*
* @category Body Types
* @param contents - The body contents
*/
body(this: Self & Wretch<Self, Chain, Resolver>, contents: any): this
/**
* Sets the "Content-Type" header, stringifies an object and sets the request body.
*
* ```js
* const jsonObject = { a: 1, b: 2, c: 3 };
* wretch("...").json(jsonObject).post();
* // Note that calling an 'http verb' method with an object argument is equivalent:
* wretch("...").post(jsonObject);
* ```
*
* @category Body Types
* @param jsObject - An object which will be serialized into a JSON
* @param contentType - A custom content type.
*/
json(this: Self & Wretch<Self, Chain, Resolver>, jsObject: object, contentType?: string): this
/**
* Sends the request using the accumulated fetch options.
*
* Can be used to replay requests.
*
* ```js
* const reAuthOn401 = wretch()
* .catcher(401, async (error, request) => {
* // Renew credentials
* const token = await wretch("/renewtoken").get().text();
* storeToken(token);
* // Replay the original request with new credentials
* return request.auth(token).fetch().unauthorized((err) => {
* throw err;
* }).json();
* });
*
* reAuthOn401
* .get("/resource")
* .json() // <- Will only be called for the original promise
* .then(callback); // <- Will be called for the original OR the replayed promise result
* ```
*
* @category HTTP
* @param method - The HTTP method to use
* @param url - Some url to append
* @param body - Set the body. Behaviour varies depending on the argument type, an object is considered as json.
*/
fetch(this: Self & Wretch<Self, Chain, Resolver>, method?: string, url?: string, body?: any):
Resolver extends undefined ?
Chain & WretchResponseChain<Self, Chain, Resolver> :
Resolver
/**
* Performs a [GET](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET) request.
*
* ```js
* wretch("...").get();
* ```
*
* @category HTTP
*/
get(this: Self & Wretch<Self, Chain, Resolver>, url?: string):
Resolver extends undefined ?
Chain & WretchResponseChain<Self, Chain, Resolver> :
Resolver
/**
* Performs a [DELETE](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE) request.
*
* ```js
* wretch("...").delete();
* ```
*
* @category HTTP
*/
delete(this: Self & Wretch<Self, Chain, Resolver>, url?: string):
Resolver extends undefined ?
Chain & WretchResponseChain<Self, Chain, Resolver> :
Resolver
/**
* Performs a [PUT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PUT) request.
*
* ```js
* wretch("...").json({...}).put()
* ```
*
* @category HTTP
*/
put(this: Self & Wretch<Self, Chain, Resolver>, body?: any, url?: string):
Resolver extends undefined ?
Chain & WretchResponseChain<Self, Chain, Resolver> :
Resolver
/**
* Performs a [POST](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) request.
*
* ```js
* wretch("...").json({...}).post()
* ```
*
* @category HTTP
*/
post(this: Self & Wretch<Self, Chain, Resolver>, body?: any, url?: string):
Resolver extends undefined ?
Chain & WretchResponseChain<Self, Chain, Resolver> :
Resolver
/**
* Performs a [PATCH](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/PATCH) request.
*
* ```js
* wretch("...").json({...}).patch()
* ```
*
* @category HTTP
*/
patch(this: Self & Wretch<Self, Chain, Resolver>, body?: any, url?: string):
Resolver extends undefined ?
Chain & WretchResponseChain<Self, Chain, Resolver> :
Resolver
/**
* Performs a [HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD) request.
*
* ```js
* wretch("...").head();
* ```
*
* @category HTTP
*/
head(this: Self & Wretch<Self, Chain, Resolver>, url?: string):
Resolver extends undefined ?
Chain & WretchResponseChain<Self, Chain, Resolver> :
Resolver
/**
* Performs an [OPTIONS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS) request.
*
* ```js
* wretch("...").opts();
* ```
*
* @category HTTP
*/
opts(this: Self & Wretch<Self, Chain, Resolver>, url?: string):
Resolver extends undefined ?
Chain & WretchResponseChain<Self, Chain, Resolver> :
Resolver
}
/**
* The resolver interface to chaining catchers and extra methods after the request has been sent.
* Ultimately returns a Promise.
*
*/
export interface WretchResponseChain<T, Self = unknown, R = undefined> {
/**
* @private @internal
*/
_wretchReq: Wretch<T, Self, R>,
/**
* @private @internal
*/
_fetchReq: Promise<WretchResponse>,
/**
* @private @internal
*/
_sharedState: Record<any, any>,
/**
*
* The handler for the raw fetch Response.
* Check the [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Response) documentation for more details on the Response class.
*
* ```js
* wretch("...").get().res((response) => console.log(response.url));
* ```
*
* @category Response Type
*/
res: <Result = WretchResponse>(cb?: (type: WretchResponse) => Promise<Result> | Result) => Promise<Awaited<Result>>,
/**
* Read the payload and deserialize it as JSON.
*
* ```js
* wretch("...").get().json((json) => console.log(Object.keys(json)));
* ```
*
* @category Response Type
*/
json: <Result = unknown>(cb?: (type: any) => Promise<Result> | Result) => Promise<Awaited<Result>>,
/**
* Read the payload and deserialize it as a Blob.
*
* ```js
* wretch("...").get().blob(blob => …)
* ```
*
* @category Response Type
*/
blob: <Result = Blob>(cb?: (type: Blob) => Promise<Result> | Result) => Promise<Awaited<Result>>,
/**
* Read the payload and deserialize it as a FormData object.
*
* ```js
* wretch("...").get().formData(formData => …)
* ```
*
* @category Response Type
*/
formData: <Result = FormData>(cb?: (type: FormData) => Promise<Result> | Result) => Promise<Awaited<Result>>,
/**
* Read the payload and deserialize it as an ArrayBuffer object.
*
* ```js
* wretch("...").get().arrayBuffer(arrayBuffer => …)
* ```
*
* @category Response Type
*/
arrayBuffer: <Result = ArrayBuffer>(cb?: (type: ArrayBuffer) => Promise<Result> | Result) => Promise<Awaited<Result>>,
/**
* Retrieves the payload as a string.
*
* ```js
* wretch("...").get().text((txt) => console.log(txt));
* ```
*
* @category Response Type
*/
text: <Result = string>(cb?: (type: string) => Promise<Result> | Result) => Promise<Awaited<Result>>,
/**
* Catches an http response with a specific error code or name and performs a callback.
*
* The original request is passed along the error and can be used in order to
* perform an additional request.
*
* ```js
* wretch("/resource")
* .get()
* .unauthorized(async (error, req) => {
* // Renew credentials
* const token = await wretch("/renewtoken").get().text();
* storeToken(token);
* // Replay the original request with new credentials
* return req.auth(token).get().unauthorized((err) => {
* throw err;
* }).json();
* })
* .json()
* // The promise chain is preserved as expected
* // ".then" will be performed on the result of the original request
* // or the replayed one (if a 401 error was thrown)
* .then(callback);
* ```
*
* @category Catchers
*/
error: (this: Self & WretchResponseChain<T, Self, R>, code: (number | string | symbol), cb: WretchErrorCallback<T, Self, R>) => this,
/**
* Catches a bad request (http code 400) and performs a callback.
*
* _Syntactic sugar for `error(400, cb)`._
*
* @see {@link WretchResponseChain.error}
* @category Catchers
*/
badRequest: (this: Self & WretchResponseChain<T, Self, R>, cb: WretchErrorCallback<T, Self, R>) => this,
/**
* Catches an unauthorized request (http code 401) and performs a callback.
*
* _Syntactic sugar for `error(401, cb)`._
*
* @see {@link WretchResponseChain.error}
* @category Catchers
*/
unauthorized: (this: Self & WretchResponseChain<T, Self, R>, cb: WretchErrorCallback<T, Self, R>) => this,
/**
* Catches a forbidden request (http code 403) and performs a callback.
*
* _Syntactic sugar for `error(403, cb)`._
*
* @see {@link WretchResponseChain.error}
* @category Catchers
*/
forbidden: (this: Self & WretchResponseChain<T, Self, R>, cb: WretchErrorCallback<T, Self, R>) => this,
/**
* Catches a "not found" request (http code 404) and performs a callback.
*
* _Syntactic sugar for `error(404, cb)`._
*
* @see {@link WretchResponseChain.error}
* @category Catchers
*/
notFound: (this: Self & WretchResponseChain<T, Self, R>, cb: WretchErrorCallback<T, Self, R>) => this,
/**
* Catches a timeout (http code 408) and performs a callback.
*
*
* _Syntactic sugar for `error(408, cb)`._
*
* @see {@link WretchResponseChain.error}
* @category Catchers
*/
timeout: (this: Self & WretchResponseChain<T, Self, R>, cb: WretchErrorCallback<T, Self, R>) => this,
/**
* Catches an internal server error (http code 500) and performs a callback.
*
*
* _Syntactic sugar for `error(500, cb)`._
*
* @see {@link WretchResponseChain.error}
* @category Catchers
*/
internalError: (this: Self & WretchResponseChain<T, Self, R>, cb: WretchErrorCallback<T, Self, R>) => this,
/**
* Catches any error thrown by the fetch function and perform the callback.
*
* @see {@link WretchResponseChain.error}
* @category Catchers
*/
fetchError: (this: Self & WretchResponseChain<T, Self, R>, cb: WretchErrorCallback<T, Self, R>) => this,
}
/**
* Configuration object.
*/
export type Config = {
options: {};
errorType: string;
polyfills: {};
polyfill(p: string, doThrow?: boolean, instance?: boolean, ...args: any[]): any;
}
/**
* Fetch Request options with additional properties.
*/
export type WretchOptions = Record<string, any>
/**
* An Error enhanced with status, text and body.
*/
export interface WretchError extends Error { status: number, response: WretchResponse, url: string, text?: string, json?: any }
/**
* Callback provided to catchers on error. Contains the original wretch instance used to perform the request.
*/
export type WretchErrorCallback<T, C, R> = (error: WretchError, originalRequest: Wretch<T, C, R>) => any
/**
* Fetch Response object with additional properties.
*/
export type WretchResponse = Response & { [key: string]: any }
/**
* Callback provided to the defer function allowing to chain deferred actions that will be stored and applied just before the request is sent.
*/
export type WretchDeferredCallback<T, C, R> = (wretch: T & Wretch<T, C, R>, url: string, options: WretchOptions) => Wretch<T, C, any>
/**
* Shape of a typical middleware.
* Expects options and returns a ConfiguredMiddleware that can then be registered using the .middlewares function.
*/
export type Middleware = (options?: { [key: string]: any }) => ConfiguredMiddleware
/**
* A ready to use middleware which is called before the request is sent.
* Input is the next middleware in the chain, then url and options.
* Output is a promise.
*/
export type ConfiguredMiddleware = (next: FetchLike) => FetchLike
/**
* Any function having the same shape as fetch().
*/
export type FetchLike = (url: string, opts: WretchOptions) => Promise<WretchResponse>
/**
* An addon enhancing either the request or response chain (or both).
*/
export type WretchAddon<W extends unknown, R extends unknown = unknown> = {
beforeRequest?<T, C, R>(wretch: T & Wretch<T, C, R>, options: WretchOptions, state: Record<any, any>): T & Wretch<T, C, R>,
wretch?: W,
resolver?: R
}