Last active
January 27, 2024 14:38
-
-
Save yevmoroz/3e02a136e793207f9b3916804e2183b0 to your computer and use it in GitHub Desktop.
basic fetch utils
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
/** | |
* Makes fetch call to API | |
* @param url | |
* @throws {ApiError} | |
*/ | |
export const fetchApi = async (url: string) => { | |
const response = await fetch(url, { | |
headers: { | |
Accept: 'application/json', | |
'Content-Type': 'application/json', | |
}, | |
}); | |
if (!response.ok) { | |
throw new ApiError(response); | |
} | |
return await response.json(); | |
}; | |
/** | |
* Generic ApiError that uses Response from generic fetch to build a meaningful error message | |
*/ | |
export class ApiError extends Error { | |
constructor(response: Response) { | |
super(`Failed fetching URL: ${response.url}`); | |
this.name = 'ApiError'; | |
this.status = response.status; | |
this.response = response; | |
} | |
status: number; | |
response: Response; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment