Add default headers]
(object?
= {}
)
function
:
a fetch-like function
import {addDefaultHeader, defaultHeaders} from 'higher-order-fetch/hofs/defaultHeaders'
const fetch = defaultHeaders({
"Content-Type": "application/json",
})(window.fetch)
// called after login success:
addDefaultHeader('Authorization', 'Basic Ym9zY236Ym9zY28=')
// below request should have 2 headers added from above:
fetch('http://example.com/data')
.then(response => response.json())
.then(data => { ... })
Manage interceptors - to do something before or after every fetch. Use this with addBeforeRequestInterceptor() and addAfterResonseInterceptor()
import {
addBeforeRequestInterceptor,
addAfterResonseInterceptor,
interceptor
} from 'higher-order-fetch/hofs/interceptor'
const fetch = interceptor()(window.fetch)
addBeforeRequestInterceptor(() => {
Loader.show()
})
addAfterResonseInterceptor(() => {
Loader.hide()
})
fetch('http://my.url/data')
.then(response => response.json())
.then(data => {...})
To define something to do before every fetch request.
If any interceptor returns false, the process will be stop immediately.
Only work with interceptor
(function)
callback that will be called before every request
function
:
Callback to remove added interceptor
To define something to do after every fetch response.
If any interceptor returns false, the process will be stop immediately.
Only work with interceptor
(function)
callback that will be called after every response
Implicitly parse response to json. The fetch created by this will resolve an array of [jsonData, statusCode]
(boolean
= false
)
If true, no error will be logged when request error or parse JSON fail.
function
:
a fetch-like function
import {jsonResponse} from 'higher-order-fetch/hofs/jsonResponse'
const fetch = jsonResponse()(window.fetch)
fetch('http://example.com/data')
.then(([data, status]) => {// no need to call `response.json()` here
// `data` is a JSON object only if fetch data success with JSON data, otherwise, it is either a Response or an Error.
// `status` is either HTTP Status Code or `undefined` if fetch fail.
})
Log request and response.
(function
= console.log
)
Your custom logger
function
:
A fetch-like function
Creat a fetch which retries when:
function
:
a fetch-like function
import {onErrorRetry} from 'higher-order-fetch/hofs/onErrorRetry'
const fetch = onErrorRetry({
maxRetry: 5,
delayMs: 3000
})(window.fetch)
fetch('http://example.com')// if request error, will retry maximum 5 times before resolve
.then(response => {
// `response` is the last response after all retries or success.
})