You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.3 KiB
53 lines
1.3 KiB
import type { CallApiArgs } from './types'
|
|
import { parseJSON } from './parseJSON'
|
|
import { checkStatus } from './checkStatus'
|
|
import { getRequestConfig } from './getRequestConfig'
|
|
import { logoutIfUnauthorized } from './logoutIfUnauthorized'
|
|
|
|
export const callApiBase = ({
|
|
abortSignal,
|
|
config,
|
|
url,
|
|
}: CallApiArgs) => {
|
|
const requestConfig = getRequestConfig(config, abortSignal)
|
|
|
|
// eslint-disable-next-line no-console
|
|
console.log(
|
|
'%c callApi from module - config ',
|
|
'color: white; background-color: #95B46A',
|
|
config,
|
|
)
|
|
|
|
return fetch(url, requestConfig)
|
|
}
|
|
|
|
const callApiWithTimeout = (args: CallApiArgs) => {
|
|
const { abortSignal, timeout } = args
|
|
const abortController = new AbortController()
|
|
const timeoutId = setTimeout(
|
|
() => abortController.abort(),
|
|
timeout,
|
|
)
|
|
|
|
if (abortSignal) {
|
|
abortSignal.addEventListener('abort', () => abortController.abort())
|
|
}
|
|
|
|
return callApiBase({
|
|
...args,
|
|
abortSignal: abortSignal || abortController.signal,
|
|
})
|
|
.then(checkStatus)
|
|
.then(parseJSON)
|
|
.catch(logoutIfUnauthorized)
|
|
.finally(() => clearTimeout(timeoutId))
|
|
}
|
|
|
|
export const callApi = (args: CallApiArgs) => {
|
|
if (args.timeout) return callApiWithTimeout(args)
|
|
|
|
return callApiBase(args)
|
|
.then(checkStatus)
|
|
.then(parseJSON)
|
|
.catch(logoutIfUnauthorized)
|
|
}
|
|
|