Created
April 19, 2023 08:57
-
-
Save ercnshngit/88a1874eae9ba85bede2913e2d4beb6c to your computer and use it in GitHub Desktop.
Rest Api Frontend utilities
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export const BASE_URL = ""; | |
| export const baseFetch = async ( | |
| url: string, | |
| method: string = "POST", | |
| options: any, | |
| ) => { | |
| let isSuccess = false; | |
| let error = ""; | |
| let data = null; | |
| try { | |
| const response = await fetch(BASE_URL + url, { | |
| method: method, | |
| headers: { | |
| "Content-Type": "application/json", | |
| Accept: "application/json", | |
| ...options.headers, | |
| }, | |
| body: options.body, | |
| }); | |
| if (response.ok) { | |
| isSuccess = true; | |
| } | |
| data = await response.json(); | |
| if (response.status >= 400 && response.status < 600) { | |
| isSuccess = false; | |
| throw new Error(data); | |
| } | |
| return { data, isSuccess, error }; | |
| } catch (err: any) { | |
| error = err.message; | |
| return { error, isSuccess, data }; | |
| } | |
| }; | |
| export const getToken = async ( | |
| url: string, | |
| data: { [key: string]: any }, | |
| ) => { | |
| return await baseFetch( | |
| url, | |
| "POST", | |
| { | |
| body: JSON.stringify(data), | |
| } | |
| ); | |
| }; | |
| export const post = async ( | |
| url: string, | |
| data: { [key: string]: any }, | |
| token: string | |
| ) => { | |
| return await baseFetch(url, "POST", { | |
| body: JSON.stringify(data), | |
| headers: { | |
| Authorization: "Bearer " + token, | |
| }, | |
| }); | |
| }; | |
| export const postWithoutToken = async ( | |
| url: string, | |
| data: { [key: string]: any } | |
| ) => { | |
| return await baseFetch(url, "POST", { | |
| body: JSON.stringify(data), | |
| }); | |
| }; | |
| export const get = async (url: string, token: string) => { | |
| return await baseFetch(url, "GET", { | |
| headers: { | |
| Authorization: "Bearer " + token, | |
| }, | |
| }); | |
| }; | |
| export const remove = async (url: string, token: string) => { | |
| return await baseFetch(url, "GET", { | |
| headers: { | |
| Authorization: "Bearer " + token, | |
| }, | |
| }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment