Commit 8df748ef authored by Alejandro Celaya's avatar Alejandro Celaya Committed by Alejandro Celaya

Migrate fetch module to TS

parent 51fc42a3
......@@ -8,16 +8,19 @@
* - Failures to parse the response in the expected format (eg. JSON)
*/
export class FetchError extends Error {
url: string;
response: Response | null;
reason: string;
/**
* @param {string} url - The URL that was requested. This may be different
* than the final URL of the response if a redirect happened.
* @param {Response|null} response - The response to the `fetch` request or
* `null` if the fetch failed
* @param {string} [reason] - Additional details about the error. This might
* include context of the network request or a server-provided error in
* the response.
* @param url - The URL that was requested. This may be different than the
* final URL of the response if a redirect happened.
* @param response - The response to the `fetch` request or `null` if the
* fetch failed
* @param reason - Additional details about the error. This might include
* context of the network request or a server-provided error in the response.
*/
constructor(url, response, reason = '') {
constructor(url: string, response: Response | null, reason = '') {
let message = 'Network request failed';
if (response) {
message += ` (${response.status})`;
......@@ -39,13 +42,15 @@ export class FetchError extends Error {
* fetchJSON wraps the browser's `fetch` API to standardize error handling when
* making network requests that return JSON responses.
*
* @param {string} url
* @param {RequestInit} [init] - Parameters for `fetch` request
* @return {Promise<unknown>} - Parsed JSON response or `null` if response status is 204 (No Content)
* @param init - Parameters for `fetch` request
* @return Parsed JSON response or `null` if response status is 204 (No Content)
* @throws {FetchError} if the request fails, returns a non-2xx status or a JSON
* response is expected but cannot be parsed
*/
export async function fetchJSON(url, init) {
export async function fetchJSON(
url: string,
init?: RequestInit
): Promise<unknown> {
let response;
try {
response = await fetch(url, init);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment