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 @@ ...@@ -8,16 +8,19 @@
* - Failures to parse the response in the expected format (eg. JSON) * - Failures to parse the response in the expected format (eg. JSON)
*/ */
export class FetchError extends Error { export class FetchError extends Error {
url: string;
response: Response | null;
reason: string;
/** /**
* @param {string} url - The URL that was requested. This may be different * @param url - The URL that was requested. This may be different than the
* than the final URL of the response if a redirect happened. * final URL of the response if a redirect happened.
* @param {Response|null} response - The response to the `fetch` request or * @param response - The response to the `fetch` request or `null` if the
* `null` if the fetch failed * fetch failed
* @param {string} [reason] - Additional details about the error. This might * @param reason - Additional details about the error. This might include
* include context of the network request or a server-provided error in * context of the network request or a server-provided error in the response.
* the response.
*/ */
constructor(url, response, reason = '') { constructor(url: string, response: Response | null, reason = '') {
let message = 'Network request failed'; let message = 'Network request failed';
if (response) { if (response) {
message += ` (${response.status})`; message += ` (${response.status})`;
...@@ -39,13 +42,15 @@ export class FetchError extends Error { ...@@ -39,13 +42,15 @@ export class FetchError extends Error {
* fetchJSON wraps the browser's `fetch` API to standardize error handling when * fetchJSON wraps the browser's `fetch` API to standardize error handling when
* making network requests that return JSON responses. * making network requests that return JSON responses.
* *
* @param {string} url * @param init - Parameters for `fetch` request
* @param {RequestInit} [init] - Parameters for `fetch` request * @return Parsed JSON response or `null` if response status is 204 (No Content)
* @return {Promise<unknown>} - 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 * @throws {FetchError} if the request fails, returns a non-2xx status or a JSON
* response is expected but cannot be parsed * 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; let response;
try { try {
response = await fetch(url, init); 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