Repository URL to install this package:
|
Version:
1.0.0-rc.13 ▾
|
/**
* Fetch error handler
* @todo Do proper error handling here
* @param {*} error - Error response from the API
* @throws Will throw passed error
*/
const errorHandler = error => {
throw error;
};
/**
* Fetch response handler
* @async
* @param {Response} response - Response from the API
* @return {Promise<*>} Parsed response data
*/
const responseHandler = async response => {
const {
headers,
status
} = response;
const contentType = headers.get('content-type');
const isJson = contentType && contentType.includes('application/json');
if (status >= 200 && status < 300) {
return isJson ? response.json() : response.text();
} // Reject in case of an error
const error = await (isJson ? response.json() : response.text());
return Promise.reject(error);
};
/**
* A custom Fetch wrapper implementation
* @async
* @param {Object} request - Request passed
* @param {string} request.url - Endpoint url
* @param {string} [request.method=GET] - Fetch method
* @param {Object} [request.headers={}] - Object with header attributes required for the request
* @param {?string} [request.body=null] - Body of the request. Note: Objects must be stringified in advance
* @param {?boolean} [request.asBeacon=false] - Tries to send a simpler beacon if API is available in browser
* @return {Promise<*|boolean>} Payload response in case of a request or queueing success flag in case of a beacon
*/
const fetchApi = async ({
url,
method = 'GET',
headers = {},
body = null,
asBeacon = false
}) => {
try {
if (asBeacon && navigator.sendBeacon) {
const contentTypeKey = 'Content-Type';
const {
[contentTypeKey]: type,
...restHeaders
} = headers;
const formattedHeaders = {
type,
...restHeaders
};
const beacon = new Blob([JSON.stringify(body)], formattedHeaders);
const isBeaconQueued = navigator.sendBeacon(url, beacon);
return isBeaconQueued;
}
const response = await fetch(url, {
method,
headers,
body
});
return await responseHandler(response);
} catch (error) {
return errorHandler(error);
}
};
export { errorHandler, fetchApi, responseHandler };
//# sourceMappingURL=fetch.js.map