Fetch function

HTML
<html></html>
CSS
JAVASCRIPT
import axios from "axios"; import { currentEnvironment } from "../environments"; import { requestInProgress } from "./endPoints"; import { Auth } from "aws-amplify"; // import authState from "../store/authState"; import networkErrorStore from "../store/networkErrorStore"; let apiBaseUrls = { local: "", dev: "", qa: "", uat: "", prod: "", staging: "", }; const baseUrl = apiBaseUrls[currentEnvironment]; const defaultHeaders = { "Content-Type": "application/json", }; let getToken = async () => { let jwtToken = ""; let user = await Auth.currentAuthenticatedUser(); const signInUserSession = user.getSignInUserSession(); jwtToken = signInUserSession ? signInUserSession.getIdToken() : null; return jwtToken.jwtToken; }; const getHeaders = async () => { // if (authState.authDataUser) { // let token = authState.authDataUser.idToken.jwtToken; // if (token) { defaultHeaders.Authorization = "Bearer " + (await getToken()); // } // } return defaultHeaders; }; export async function Fetch( endpoint, data, type = "get", endpointName, reqHeaders, baseurl = baseUrl ) { const CancelToken = axios.CancelToken; let headers = await getHeaders(); if (reqHeaders) { headers = { ...headers, ...reqHeaders }; } return await finalFetch({ method: type, url: endpoint, baseURL: baseurl, data: data, headers: headers, cancelToken: new CancelToken(function executor(c) { // An executor function receives a cancel function as a parameter endpointName && (requestInProgress[endpointName] = c); }), }); } export default async function finalFetch(config) { return axios(config) .then((response) => { if ( response.data.status !== 0 && !response.data.message.includes("already exists") ) { networkErrorStore.setNetworkError( "Error Fetching Data for " + config.url ); } return response.data; }) .catch((error) => { if (error.message === "Network Error" && !error.response) { console.log("Network error - problem communicating with API"); } else if (error.response) { const { status, data, config } = error.response; if (status === 404) { console.log("/notfound"); } if ( status === 400 && config.method === "get" && data.errors.hasOwnProperty("id") ) { console.log("/notfound"); } if (status === 500) { console.log("Server error - check the terminal for more info!"); } networkErrorStore.setNetworkError( "Error Fetching Data for " + config.url + "giving status " + status ); } throw error; }) .finally(() => {}); }
Expand for more options Login