es-fetcher
Version:
Enhance your frontend application's API implementation and calls with es-fetcher. Simplify and accelerate the process like never before.
95 lines (94 loc) • 4.93 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { useEffect, useState } from 'react';
import { chooseProperties, constructAbsoluteUrl, isAbsoluteUrl, omitProperties, tryParsingBody } from './utils';
import { clearMemoryCache, deleteMemoryCache, deleteMemoryCaches, memoryCacheData } from './fetch-memory-cache';
/**
* Global configuration fetch.
*
* @type {FetchConfiguration}
*/
export let configuration = { baseUrl: location === null || location === void 0 ? void 0 : location.origin };
/**
* Configures the global fetch settings.
*
* @param {FetchConfiguration} fetchConfiguration - Global fetch settings, as defined in the `FetchConfiguration` interface.
*/
const configureFetcher = (fetchConfiguration) => {
configuration = Object.assign(Object.assign({}, configuration), fetchConfiguration);
};
/**
* Create an absolute URL based on the base URL and provided URL.
*
* @param {string} url - Relative or absolute URL.
* @param {string} [base] - Optional base URL.
* @returns {string} - The absolute URL.
*/
const createAbsoluteUrl = (url, base) => constructAbsoluteUrl(url, base || configuration.baseUrl);
/**
* Makes fetch request using the provided URL and options and returns the fetched data.
*
* @param {string} url - The URL to fetch data from. It can be either an absolute or relative URL.
* @param {FetchOptions} [options] - Custom options for the fetch request, as defined in the `FetchOptions` interface.
* @returns {Promise<any>} - A promise that resolves with the fetched data.
*/
export const fetchData = (url, options = {}) => new Promise((onSuccess, onFailed) => {
if (!isAbsoluteUrl(url))
url = createAbsoluteUrl(url);
let { baseUrl, cache } = configuration;
if (options.cache) {
cache = options.cache;
if (cache === 'memory-cache')
options = omitProperties(options, ['cache']);
}
let cachedData, cacheable = cache === 'memory-cache' && (!options.method || options.method === 'GET');
if (cacheable && (cachedData = memoryCacheData[url]))
onSuccess(cachedData);
else if (baseUrl && url.startsWith(baseUrl)) {
const { accessToken, authMethod, headers } = configuration;
options = Object.assign(Object.assign(Object.assign(Object.assign({}, (cache && cache !== 'memory-cache' ? { cache } : {})), (chooseProperties(configuration, ['mode', 'credentials']))), options), { headers: Object.assign(Object.assign({}, (options.body ? (headers || {}) : omitProperties(headers || {}, ['Content-Type']))), (options.headers || {})) });
if (authMethod === 'bearer' && accessToken)
options.headers['Authorization'] = `Bearer ${accessToken}`;
fetch(url, options).then((fetchResults) => __awaiter(void 0, void 0, void 0, function* () {
const body = yield tryParsingBody(fetchResults).catch(() => { });
if (cacheable || (memoryCacheData.hasOwnProperty(url) && (!options.method || options.method === 'GET')))
memoryCacheData[url] = body;
if (fetchResults.ok)
onSuccess(body);
else
onFailed(body);
})).catch(exception => {
onFailed(exception);
});
}
});
/**
* A custom React hook for making API requests and managing loading state.
*
* @param {string} url - The URL to fetch data from. It can be either an absolute or relative URL.
* @param {FetchOptions} [options] - Custom options for the fetch request, as defined in the FetchOptions interface.
* @returns {{ loading: boolean, fetchedData: any, error?: string }} - An object containing loading state, data, and error.
*/
const useFetch = (url, options) => {
const [loading, setLoading] = useState(true);
const [fetchedData, setFetchedData] = useState();
const [error, setError] = useState();
useEffect(() => {
fetchData(url, options).then((fetchData) => {
setFetchedData(fetchData);
setLoading(false);
}).catch((error) => {
setError(error.message);
setLoading(false);
});
}, [url, options]);
return { loading, fetchedData, error };
};
export { fetchData as fetch, useFetch, configureFetcher, deleteMemoryCache, deleteMemoryCaches, clearMemoryCache, createAbsoluteUrl };