Skip to content

Instantly share code, notes, and snippets.

@ramirezsandin
Created July 29, 2022 10:09
Show Gist options
  • Save ramirezsandin/19f6aff700b972bf1c018e2e474a8233 to your computer and use it in GitHub Desktop.
Save ramirezsandin/19f6aff700b972bf1c018e2e474a8233 to your computer and use it in GitHub Desktop.
Custom Fetch library
async function http<T>(url: string, config: RequestInit): Promise<T> {
const request = new Request(url, config);
const response = await fetch(request);
if (!response.ok) {
const err = new Error(response.statusText);
err.name = 'HTTPError';
throw err;
}
return await response.json().catch(() => ({}));
}
export async function getFetch<T>(
path: string,
config?: RequestInit,
): Promise<T> {
console.log(`Doing GET fetch @ ${path}`);
const init = {
method: 'GET',
...config,
};
return await http<T>(path, init);
}
export async function postFetch<T, U>(
path: string,
body: T,
config?: RequestInit,
): Promise<U> {
const init = {
method: 'POST',
body: JSON.stringify(body),
...config,
};
return await http<U>(path, init);
}
export async function putFetch<T, U>(
path: string,
body: T,
config?: RequestInit,
): Promise<U> {
const init = {
method: 'PUT',
body: JSON.stringify(body),
...config,
};
return await http<U>(path, init);
}
export async function patchFetch<T, U>(
path: string,
body: T,
config?: RequestInit,
): Promise<U> {
const init = {
method: 'PATCH',
body: JSON.stringify(body),
...config,
};
return await http<U>(path, init);
}
export async function deleteFetch<T, U>(
path: string,
body?: T,
config?: RequestInit,
): Promise<U> {
const init = {
method: 'DELETE',
...config,
};
if (body) {
init.body = JSON.stringify(body);
}
return await http<U>(path, init);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment