From 40ccc1c9c6040b4854b656a1ba85a90f74f00f6c Mon Sep 17 00:00:00 2001 From: cris lombardo Date: Tue, 23 Jan 2024 13:20:35 -0500 Subject: [PATCH] refactor: add constants file and revert from axios to fetch --- src/app/lib/utils.tsx | 62 ++++++++++++++++++++++++------------------- src/constants.ts | 3 +++ 2 files changed, 38 insertions(+), 27 deletions(-) create mode 100644 src/constants.ts diff --git a/src/app/lib/utils.tsx b/src/app/lib/utils.tsx index 966d4f8..e23ab36 100644 --- a/src/app/lib/utils.tsx +++ b/src/app/lib/utils.tsx @@ -1,5 +1,6 @@ import { faker } from '@faker-js/faker'; import axios from 'axios'; +import { serverUrl } from '../../constants'; export const positionEnding = (position: number | string) => { // Convert to int @@ -118,12 +119,11 @@ const dataConfig: DataConfigSchema = { }, }; -const serverURL = 'http://127.0.0.1:8081'; export const fetchAPI = async ( endpoint: string, statusCheck: boolean = false, ) => { - const server = statusCheck || document.body.classList.contains('server'); + const useServer = statusCheck || document.body.classList.contains('server'); // Headers for statusCheck so const options = statusCheck ? { headers: { cache: 'no-store' } } : {}; @@ -134,32 +134,40 @@ export const fetchAPI = async ( ] || false; // If we are not using the server return the dummy data - if (!server) { + if (!useServer) { return dummy; - } else { - // Fetch from server - const data = await axios(`${serverURL}/${endpoint}`, options) - .then( - (res) => { - // Response is not successful - if (res.statusText !== 'OK') { - throw new Error('Not 2xx response', { cause: res }); - } - // Sucess - parse data - return res.data; - }, - // Catch initial fetch error - (err) => { - throw new Error('Server not connecting', { cause: err }); - }, - ) - // Return parsed data - .then((data) => data) - // Catch errors from above - .catch(() => { + } + + // Fetch from server + const data = await fetch(`${serverUrl}/${endpoint}`, { ...options }) + .then( + (res) => { + // Response is not successful + if (!res.ok) { + throw new Error('Not 2xx response', { cause: res }); + } + + // Success parse data + return res.json(); + }, + // Catch initial fetch error + (err) => { + throw new Error('Server not connecting', { cause: err }); + }, + ) + // Return parsed data + .then((data) => data) + // Catch errors from above + .catch((err) => { + if (err === 'Server not connecting') + return dummy; + if (err.status === 404) return dummy; - }); - return data; - } + return dummy; + }); + + // console.log('data', data) + + return data; }; diff --git a/src/constants.ts b/src/constants.ts new file mode 100644 index 0000000..69f76d3 --- /dev/null +++ b/src/constants.ts @@ -0,0 +1,3 @@ +const serverUrl = 'http://127.0.0.1:8081'; + +export { serverUrl };