Skip to content

Instantly share code, notes, and snippets.

@tkim90
Last active September 27, 2023 13:00
Show Gist options
  • Select an option

  • Save tkim90/46de72c8353a4c79b93f66e04f50febf to your computer and use it in GitHub Desktop.

Select an option

Save tkim90/46de72c8353a4c79b93f66e04f50febf to your computer and use it in GitHub Desktop.
typescript fetch pattern
// Source: https://www.carlrippon.com/fetch-with-async-await-and-typescript/
// Source: https://eckertalex.dev/blog/typescript-fetch-wrapper
interface HttpResponse<T> extends Response {
parsedBody?: T;
error?: T;
}
export async function http<T>(request: RequestInfo): Promise<HttpResponse<T>> {
const response: HttpResponse<T> = await fetch(request);
try {
// may error if there is no body
response.parsedBody = await response.json();
} catch (err) {
console.error(err);
}
if (!response.ok) {
throw new Error(response.statusText);
}
console.log(response);
return response;
}
export async function get<T>(
path: string,
args: RequestInit = { method: 'get' },
): Promise<HttpResponse<T>> {
return await http<T>(new Request(path, args));
}
export async function post<T>(
path: string,
body: any,
args: RequestInit = {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
},
): Promise<HttpResponse<T>> {
console.log(body);
return await http<T>(new Request(path, args));
}
export async function put<T>(
path: string,
body: any,
args: RequestInit = { method: "put", body: JSON.stringify(body) }
): Promise<HttpResponse<T>> {
return await http<T>(new Request(path, args));
};
// example consuming code
const response = await post<{ id: number }>(
"https://jsonplaceholder.typicode.com/posts",
{ title: "my post", body: "some content" }
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment