| 1 |
import { joinUrls } from './utils' |
| 2 |
import { isPlainObject } from './core/rtkImports' |
| 3 |
import type { BaseQueryApi, BaseQueryFn } from './baseQueryTypes' |
| 4 |
import type { MaybePromise, Override } from './tsHelpers' |
| 5 |
|
| 6 |
export type ResponseHandler = |
| 7 |
| 'content-type' |
| 8 |
| 'json' |
| 9 |
| 'text' |
| 10 |
| ((response: Response) => Promise<any>) |
| 11 |
|
| 12 |
type CustomRequestInit = Override< |
| 13 |
RequestInit, |
| 14 |
{ |
| 15 |
headers?: |
| 16 |
| Headers |
| 17 |
| string[][] |
| 18 |
| Record<string, string | undefined> |
| 19 |
| undefined |
| 20 |
} |
| 21 |
> |
| 22 |
|
| 23 |
export interface FetchArgs extends CustomRequestInit { |
| 24 |
url: string |
| 25 |
params?: Record<string, any> |
| 26 |
body?: any |
| 27 |
responseHandler?: ResponseHandler |
| 28 |
validateStatus?: (response: Response, body: any) => boolean |
| 29 |
/** |
| 30 |
* A number in milliseconds that represents that maximum time a request can take before timing out. |
| 31 |
*/ |
| 32 |
timeout?: number |
| 33 |
} |
| 34 |
|
| 35 |
/** |
| 36 |
* A mini-wrapper that passes arguments straight through to |
| 37 |
* {@link [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)}. |
| 38 |
* Avoids storing `fetch` in a closure, in order to permit mocking/monkey-patching. |
| 39 |
*/ |
| 40 |
const defaultFetchFn: typeof fetch = (...args) => fetch(...args) |
| 41 |
|
| 42 |
const defaultValidateStatus = (response: Response) => |
| 43 |
response.status >= 200 && response.status <= 299 |
| 44 |
|
| 45 |
const defaultIsJsonContentType = (headers: Headers) => |
| 46 |
/*applicat*/ /ion\/(vnd\.api\+)?json/.test(headers.get('content-type') || '') |
| 47 |
|
| 48 |
export type FetchBaseQueryError = |
| 49 |
| { |
| 50 |
/** |
| 51 |
* * `number`: |
| 52 |
* HTTP status code |
| 53 |
*/ |
| 54 |
status: number |
| 55 |
data: unknown |
| 56 |
} |
| 57 |
| { |
| 58 |
/** |
| 59 |
* * `"FETCH_ERROR"`: |
| 60 |
* An error that occurred during execution of `fetch` or the `fetchFn` callback option |
| 61 |
**/ |
| 62 |
status: 'FETCH_ERROR' |
| 63 |
data?: undefined |
| 64 |
error: string |
| 65 |
} |
| 66 |
| { |
| 67 |
/** |
| 68 |
* * `"PARSING_ERROR"`: |
| 69 |
* An error happened during parsing. |
| 70 |
* Most likely a non-JSON-response was returned with the default `responseHandler` "JSON", |
| 71 |
* or an error occurred while executing a custom `responseHandler`. |
| 72 |
**/ |
| 73 |
status: 'PARSING_ERROR' |
| 74 |
originalStatus: number |
| 75 |
data: string |
| 76 |
error: string |
| 77 |
} |
| 78 |
| { |
| 79 |
/** |
| 80 |
* * `"TIMEOUT_ERROR"`: |
| 81 |
* Request timed out |
| 82 |
**/ |
| 83 |
status: 'TIMEOUT_ERROR' |
| 84 |
data?: undefined |
| 85 |
error: string |
| 86 |
} |
| 87 |
| { |
| 88 |
/** |
| 89 |
* * `"CUSTOM_ERROR"`: |
| 90 |
* A custom error type that you can return from your `queryFn` where another error might not make sense. |
| 91 |
**/ |
| 92 |
status: 'CUSTOM_ERROR' |
| 93 |
data?: unknown |
| 94 |
error: string |
| 95 |
} |
| 96 |
|
| 97 |
function stripUndefined(obj: any) { |
| 98 |
if (!isPlainObject(obj)) { |
| 99 |
return obj |
| 100 |
} |
| 101 |
const copy: Record<string, any> = { ...obj } |
| 102 |
for (const [k, v] of Object.entries(copy)) { |
| 103 |
if (v === undefined) delete copy[k] |
| 104 |
} |
| 105 |
return copy |
| 106 |
} |
| 107 |
|
| 108 |
export type FetchBaseQueryArgs = { |
| 109 |
baseUrl?: string |
| 110 |
prepareHeaders?: ( |
| 111 |
headers: Headers, |
| 112 |
api: Pick< |
| 113 |
BaseQueryApi, |
| 114 |
'getState' | 'extra' | 'endpoint' | 'type' | 'forced' |
| 115 |
> & { arg: string | FetchArgs; extraOptions: unknown }, |
| 116 |
) => MaybePromise<Headers | void> |
| 117 |
fetchFn?: ( |
| 118 |
input: RequestInfo, |
| 119 |
init?: RequestInit | undefined, |
| 120 |
) => Promise<Response> |
| 121 |
paramsSerializer?: (params: Record<string, any>) => string |
| 122 |
/** |
| 123 |
* By default, we only check for 'application/json' and 'application/vnd.api+json' as the content-types for json. If you need to support another format, you can pass |
| 124 |
* in a predicate function for your given api to get the same automatic stringifying behavior |
| 125 |
* @example |
| 126 |
* ```ts |
| 127 |
* const isJsonContentType = (headers: Headers) => ["application/vnd.api+json", "application/json", "application/vnd.hal+json"].includes(headers.get("content-type")?.trim()); |
| 128 |
* ``` |
| 129 |
*/ |
| 130 |
isJsonContentType?: (headers: Headers) => boolean |
| 131 |
/** |
| 132 |
* Defaults to `application/json`; |
| 133 |
*/ |
| 134 |
jsonContentType?: string |
| 135 |
|
| 136 |
/** |
| 137 |
* Custom replacer function used when calling `JSON.stringify()`; |
| 138 |
*/ |
| 139 |
jsonReplacer?: (this: any, key: string, value: any) => any |
| 140 |
} & RequestInit & |
| 141 |
Pick<FetchArgs, 'responseHandler' | 'validateStatus' | 'timeout'> |
| 142 |
|
| 143 |
export type FetchBaseQueryMeta = { request: Request; response?: Response } |
| 144 |
|
| 145 |
/** |
| 146 |
* This is a very small wrapper around fetch that aims to simplify requests. |
| 147 |
* |
| 148 |
* @example |
| 149 |
* ```ts |
| 150 |
* const baseQuery = fetchBaseQuery({ |
| 151 |
* baseUrl: 'https://api.your-really-great-app.com/v1/', |
| 152 |
* prepareHeaders: (headers, { getState }) => { |
| 153 |
* const token = (getState() as RootState).auth.token; |
| 154 |
* // If we have a token set in state, let's assume that we should be passing it. |
| 155 |
* if (token) { |
| 156 |
* headers.set('authorization', `Bearer ${token}`); |
| 157 |
* } |
| 158 |
* return headers; |
| 159 |
* }, |
| 160 |
* }) |
| 161 |
* ``` |
| 162 |
* |
| 163 |
* @param {string} baseUrl |
| 164 |
* The base URL for an API service. |
| 165 |
* Typically in the format of https://example.com/ |
| 166 |
* |
| 167 |
* @param {(headers: Headers, api: { getState: () => unknown; arg: string | FetchArgs; extra: unknown; endpoint: string; type: 'query' | 'mutation'; forced: boolean; }) => Headers} prepareHeaders |
| 168 |
* An optional function that can be used to inject headers on requests. |
| 169 |
* Provides a Headers object, most of the `BaseQueryApi` (`dispatch` is not available), and the arg passed into the query function. |
| 170 |
* Useful for setting authentication or headers that need to be set conditionally. |
| 171 |
* |
| 172 |
* @link https://developer.mozilla.org/en-US/docs/Web/API/Headers |
| 173 |
* |
| 174 |
* @param {(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>} fetchFn |
| 175 |
* Accepts a custom `fetch` function if you do not want to use the default on the window. |
| 176 |
* Useful in SSR environments if you need to use a library such as `isomorphic-fetch` or `cross-fetch` |
| 177 |
* |
| 178 |
* @param {(params: Record<string, unknown>) => string} paramsSerializer |
| 179 |
* An optional function that can be used to stringify querystring parameters. |
| 180 |
* |
| 181 |
* @param {(headers: Headers) => boolean} isJsonContentType |
| 182 |
* An optional predicate function to determine if `JSON.stringify()` should be called on the `body` arg of `FetchArgs` |
| 183 |
* |
| 184 |
* @param {string} jsonContentType Used when automatically setting the content-type header for a request with a jsonifiable body that does not have an explicit content-type header. Defaults to `application/json`. |
| 185 |
* |
| 186 |
* @param {(this: any, key: string, value: any) => any} jsonReplacer Custom replacer function used when calling `JSON.stringify()`. |
| 187 |
* |
| 188 |
* @param {number} timeout |
| 189 |
* A number in milliseconds that represents the maximum time a request can take before timing out. |
| 190 |
*/ |
| 191 |
|
| 192 |
export function fetchBaseQuery({ |
| 193 |
baseUrl, |
| 194 |
prepareHeaders = (x) => x, |
| 195 |
fetchFn = defaultFetchFn, |
| 196 |
paramsSerializer, |
| 197 |
isJsonContentType = defaultIsJsonContentType, |
| 198 |
jsonContentType = 'application/json', |
| 199 |
jsonReplacer, |
| 200 |
timeout: defaultTimeout, |
| 201 |
responseHandler: globalResponseHandler, |
| 202 |
validateStatus: globalValidateStatus, |
| 203 |
...baseFetchOptions |
| 204 |
}: FetchBaseQueryArgs = {}): BaseQueryFn< |
| 205 |
string | FetchArgs, |
| 206 |
unknown, |
| 207 |
FetchBaseQueryError, |
| 208 |
{}, |
| 209 |
FetchBaseQueryMeta |
| 210 |
> { |
| 211 |
if (typeof fetch === 'undefined' && fetchFn === defaultFetchFn) { |
| 212 |
console.warn( |
| 213 |
'Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.', |
| 214 |
) |
| 215 |
} |
| 216 |
return async (arg, api, extraOptions) => { |
| 217 |
const { getState, extra, endpoint, forced, type } = api |
| 218 |
let meta: FetchBaseQueryMeta | undefined |
| 219 |
let { |
| 220 |
url, |
| 221 |
headers = new Headers(baseFetchOptions.headers), |
| 222 |
params = undefined, |
| 223 |
responseHandler = globalResponseHandler ?? ('json' as const), |
| 224 |
validateStatus = globalValidateStatus ?? defaultValidateStatus, |
| 225 |
timeout = defaultTimeout, |
| 226 |
...rest |
| 227 |
} = typeof arg == 'string' ? { url: arg } : arg |
| 228 |
|
| 229 |
let abortController: AbortController | undefined, |
| 230 |
signal = api.signal |
| 231 |
if (timeout) { |
| 232 |
abortController = new AbortController() |
| 233 |
api.signal.addEventListener('abort', abortController.abort) |
| 234 |
signal = abortController.signal |
| 235 |
} |
| 236 |
|
| 237 |
let config: RequestInit = { |
| 238 |
...baseFetchOptions, |
| 239 |
signal, |
| 240 |
...rest, |
| 241 |
} |
| 242 |
|
| 243 |
headers = new Headers(stripUndefined(headers)) |
| 244 |
config.headers = |
| 245 |
(await prepareHeaders(headers, { |
| 246 |
getState, |
| 247 |
arg, |
| 248 |
extra, |
| 249 |
endpoint, |
| 250 |
forced, |
| 251 |
type, |
| 252 |
extraOptions, |
| 253 |
})) || headers |
| 254 |
|
| 255 |
// Only set the content-type to json if appropriate. Will not be true for FormData, ArrayBuffer, Blob, etc. |
| 256 |
const isJsonifiable = (body: any) => |
| 257 |
typeof body === 'object' && |
| 258 |
(isPlainObject(body) || |
| 259 |
Array.isArray(body) || |
| 260 |
typeof body.toJSON === 'function') |
| 261 |
|
| 262 |
if (!config.headers.has('content-type') && isJsonifiable(config.body)) { |
| 263 |
config.headers.set('content-type', jsonContentType) |
| 264 |
} |
| 265 |
|
| 266 |
if (isJsonifiable(config.body) && isJsonContentType(config.headers)) { |
| 267 |
config.body = JSON.stringify(config.body, jsonReplacer) |
| 268 |
} |
| 269 |
|
| 270 |
if (params) { |
| 271 |
const divider = ~url.indexOf('?') ? '&' : '?' |
| 272 |
const query = paramsSerializer |
| 273 |
? paramsSerializer(params) |
| 274 |
: new URLSearchParams(stripUndefined(params)) |
| 275 |
url += divider + query |
| 276 |
} |
| 277 |
|
| 278 |
url = joinUrls(baseUrl, url) |
| 279 |
|
| 280 |
const request = new Request(url, config) |
| 281 |
const requestClone = new Request(url, config) |
| 282 |
meta = { request: requestClone } |
| 283 |
|
| 284 |
let response, |
| 285 |
timedOut = false, |
| 286 |
timeoutId = |
| 287 |
abortController && |
| 288 |
setTimeout(() => { |
| 289 |
timedOut = true |
| 290 |
abortController!.abort() |
| 291 |
}, timeout) |
| 292 |
try { |
| 293 |
response = await fetchFn(request) |
| 294 |
} catch (e) { |
| 295 |
return { |
| 296 |
error: { |
| 297 |
status: timedOut ? 'TIMEOUT_ERROR' : 'FETCH_ERROR', |
| 298 |
error: String(e), |
| 299 |
}, |
| 300 |
meta, |
| 301 |
} |
| 302 |
} finally { |
| 303 |
if (timeoutId) clearTimeout(timeoutId) |
| 304 |
abortController?.signal.removeEventListener( |
| 305 |
'abort', |
| 306 |
abortController.abort, |
| 307 |
) |
| 308 |
} |
| 309 |
const responseClone = response.clone() |
| 310 |
|
| 311 |
meta.response = responseClone |
| 312 |
|
| 313 |
let resultData: any |
| 314 |
let responseText: string = '' |
| 315 |
try { |
| 316 |
let handleResponseError |
| 317 |
await Promise.all([ |
| 318 |
handleResponse(response, responseHandler).then( |
| 319 |
(r) => (resultData = r), |
| 320 |
(e) => (handleResponseError = e), |
| 321 |
), |
| 322 |
// see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182 |
| 323 |
// we *have* to "use up" both streams at the same time or they will stop running in node-fetch scenarios |
| 324 |
responseClone.text().then( |
| 325 |
(r) => (responseText = r), |
| 326 |
() => {}, |
| 327 |
), |
| 328 |
]) |
| 329 |
if (handleResponseError) throw handleResponseError |
| 330 |
} catch (e) { |
| 331 |
return { |
| 332 |
error: { |
| 333 |
status: 'PARSING_ERROR', |
| 334 |
originalStatus: response.status, |
| 335 |
data: responseText, |
| 336 |
error: String(e), |
| 337 |
}, |
| 338 |
meta, |
| 339 |
} |
| 340 |
} |
| 341 |
|
| 342 |
return validateStatus(response, resultData) |
| 343 |
? { |
| 344 |
data: resultData, |
| 345 |
meta, |
| 346 |
} |
| 347 |
: { |
| 348 |
error: { |
| 349 |
status: response.status, |
| 350 |
data: resultData, |
| 351 |
}, |
| 352 |
meta, |
| 353 |
} |
| 354 |
} |
| 355 |
|
| 356 |
async function handleResponse( |
| 357 |
response: Response, |
| 358 |
responseHandler: ResponseHandler, |
| 359 |
) { |
| 360 |
if (typeof responseHandler === 'function') { |
| 361 |
return responseHandler(response) |
| 362 |
} |
| 363 |
|
| 364 |
if (responseHandler === 'content-type') { |
| 365 |
responseHandler = isJsonContentType(response.headers) ? 'json' : 'text' |
| 366 |
} |
| 367 |
|
| 368 |
if (responseHandler === 'json') { |
| 369 |
const text = await response.text() |
| 370 |
return text.length ? JSON.parse(text) : null |
| 371 |
} |
| 372 |
|
| 373 |
return response.text() |
| 374 |
} |
| 375 |
} |