Last active
September 27, 2023 13:00
-
-
Save tkim90/46de72c8353a4c79b93f66e04f50febf to your computer and use it in GitHub Desktop.
typescript fetch pattern
This file contains hidden or 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
| // 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