@@ -2,18 +2,35 @@ import { joinUrls } from './utils';
2
2
import { isPlainObject } from '@reduxjs/toolkit' ;
3
3
import { BaseQueryFn } from './apiTypes' ;
4
4
5
+ export type ResponseHandler = 'json' | 'text' | ( ( response : Response ) => Promise < any > ) ;
6
+
5
7
export interface FetchArgs extends RequestInit {
6
8
url : string ;
7
9
params ?: Record < string , any > ;
8
10
body ?: any ;
9
- responseHandler ?: 'json' | 'text' | ( ( response : Response ) => Promise < any > ) ;
11
+ responseHandler ?: ResponseHandler ;
10
12
validateStatus ?: ( response : Response , body : any ) => boolean ;
11
13
}
12
14
13
15
const defaultValidateStatus = ( response : Response ) => response . status >= 200 && response . status <= 299 ;
14
16
15
17
const isJsonContentType = ( headers : Headers ) => headers . get ( 'content-type' ) ?. trim ( ) ?. startsWith ( 'application/json' ) ;
16
18
19
+ const handleResponse = async ( response : Response , responseHandler : ResponseHandler ) => {
20
+ if ( typeof responseHandler === 'function' ) {
21
+ return responseHandler ( response ) ;
22
+ }
23
+
24
+ if ( responseHandler === 'text' ) {
25
+ return response . text ( ) ;
26
+ }
27
+
28
+ if ( responseHandler === 'json' ) {
29
+ const text = await response . text ( ) ;
30
+ return text . length ? JSON . parse ( text ) : undefined ;
31
+ }
32
+ } ;
33
+
17
34
export interface FetchBaseQueryError {
18
35
status : number ;
19
36
data : unknown ;
@@ -65,11 +82,7 @@ export function fetchBaseQuery({
65
82
url = joinUrls ( baseUrl , url ) ;
66
83
67
84
const response = await fetch ( url , config ) ;
68
-
69
- const resultData =
70
- typeof responseHandler === 'function'
71
- ? await responseHandler ( response )
72
- : await response [ responseHandler || 'text' ] ( ) ;
85
+ const resultData = await handleResponse ( response , responseHandler ) ;
73
86
74
87
return validateStatus ( response , resultData )
75
88
? { data : resultData }
0 commit comments