Last active
May 24, 2021 15:14
-
-
Save pedropalhari/3b6a0e076dc4648ea64da7e9760a3d15 to your computer and use it in GitHub Desktop.
A(uthorized) Fetch used for fast prototyping. We need only `{ error: boolean; message: string }` if there's an error on the API.
This file contains 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
// a(uthorized)fetch | |
function getAccessToken() { | |
return localStorage.getItem("@project/accessToken"); | |
} | |
function setAccessToken(token: string) { | |
localStorage.setItem("@project/accessToken", token); | |
} | |
function clearAccessToken() { | |
localStorage.removeItem("@project/accessToken"); | |
} | |
export const AccessToken = { | |
get: getAccessToken, | |
set: setAccessToken, | |
clear: clearAccessToken, | |
}; | |
async function __fetch<T>( | |
method: "GET" | "POST" | "PATCH" | "DELETE" | "PUT", | |
input: RequestInfo, | |
body?: any, | |
init?: RequestInit | |
) { | |
let accessToken = AccessToken.get(); | |
let response = await fetch(input, { | |
method, | |
headers: { | |
"Content-Type": "application/json", | |
// If I have an accessToken, use it | |
...(accessToken && { Authorization: `Bearer ${accessToken}` }), | |
}, | |
// If my method has data, and it's not a get, use it | |
...(method !== "GET" && body && { body: JSON.stringify(body) }), | |
// More options | |
...init, | |
}); | |
let responseJSON = await response.json(); | |
if (response.status !== 200) { | |
return { | |
error: true, | |
...responseJSON, | |
} as T & { error: true }; | |
} else { | |
return responseJSON as T & { error: false }; | |
} | |
} | |
const afetch = { | |
post: <T>(input: RequestInfo, body?: any, init?: RequestInit) => | |
__fetch<T>("POST", input, body, init), | |
get: <T>(input: RequestInfo, body?: any, init?: RequestInit) => | |
__fetch<T>("GET", input, body, init), | |
patch: <T>(input: RequestInfo, body?: any, init?: RequestInit) => | |
__fetch<T>("PATCH", input, body, init), | |
put: <T>(input: RequestInfo, body?: any, init?: RequestInit) => | |
__fetch<T>("PUT", input, body, init), | |
delete: <T>(input: RequestInfo, body?: any, init?: RequestInit) => | |
__fetch<T>("DELETE", input, body, init), | |
}; | |
export default afetch; |
Usage:
async function createForward(forward: Omit<Forward, "forwardId">) {
let createForwardResponse = await afetch.post<{
accessToken: string;
message?: string;
}>(`${BASE_URL}/url/forward`, {
...forward,
});
if (createForwardResponse.error) {
alert(createForwardResponse.message);
return;
} else {
return { ok: true };
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is for me, do not use it.