Skip to content

Instantly share code, notes, and snippets.

@leolanese
Created August 16, 2020 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leolanese/191c7d0cdd1d220276d06dceea4313e6 to your computer and use it in GitHub Desktop.
Save leolanese/191c7d0cdd1d220276d06dceea4313e6 to your computer and use it in GitHub Desktop.
fetch API + async-await + TypeScript
// declaring fetch + async-await + TypeScript
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", body: JSON.stringify(body) }
): Promise<HttpResponse<T>> {
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