Created
October 27, 2022 07:13
-
-
Save Klekum/965e0cc48730a38c3fae8156dd3ec3f8 to your computer and use it in GitHub Desktop.
Drop-in replacement for Axios json handler using Fetch 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
const API_BASE = "/api/v1"; | |
export function sendRequest(endpoint: string, method: string, data?: any) { | |
const reqParams: RequestInit = { method } | |
if (data) reqParams.body = new URLSearchParams(data) | |
return new Promise((resolve, reject) => { | |
fetchAuth(API_BASE + endpoint, reqParams).then(jsonResponse).then(resolve).catch(reject) | |
}) | |
} | |
export function post(endpoint: string, data?: any) { | |
return sendRequest(endpoint, "POST", data); | |
} | |
export function get(endpoint: string, data?: any) { | |
var url = new URL( window.location.protocol + "//" + window.location.host + API_BASE + endpoint); | |
for (let k in data) { url.searchParams.append(k, data[k]); } | |
return new Promise((resolve, reject) => { | |
fetchAuth(url).then(req => { | |
jsonResponse(req).then(resolve).catch(reject); | |
}).catch(reject) | |
}) | |
} | |
export function deleter(endpoint: string, data?: any) { | |
return sendRequest(endpoint, "DELETE", data); | |
} | |
export function put(endpoint: string, data?: any) { | |
return sendRequest(endpoint, "PUT", data); | |
} | |
export function patch(endpoint: string, data?: any) { | |
return sendRequest(endpoint, "PATCH", data); | |
} | |
function jsonResponse(request: any) { | |
return new Promise((resolve, reject) => { | |
request.json().then((json: any) => { | |
resolve({ data: json, request }); | |
}).catch(reject) | |
}) | |
} | |
function fetchAuth(url: URL|string, reqParams?: RequestInit) { | |
const token = localStorage.getItem("token"); | |
if(token) { | |
const authHeader = new Headers(); | |
authHeader.append('Authorization', `Bearer ${token}`); | |
if(!reqParams) { | |
reqParams = { headers: authHeader }; | |
} else { | |
reqParams.headers = authHeader; | |
} | |
} | |
return fetch(url, reqParams); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment