request.ts raw

   1  import { getAuthToken } from "src/lib/auth";
   2  import { ErrorResponse } from "src/types";
   3  
   4  export const request = async <T>(
   5    ...args: Parameters<typeof fetch>
   6  ): Promise<T | undefined> => {
   7    if (import.meta.env.BASE_URL !== "/") {
   8      // if running on a subpath, include the subpath in the request URL
   9      // BASE_URL is set via process.env.BASE_PATH, see https://vite.dev/guide/build#public-base-path
  10      args[0] = import.meta.env.BASE_URL + args[0];
  11    }
  12  
  13    const token = getAuthToken();
  14    if (token) {
  15      if (!args[1]) {
  16        args[1] = {};
  17      }
  18      args[1].headers = {
  19        ...args[1].headers,
  20        Authorization: `Bearer ${token}`,
  21      };
  22    }
  23  
  24    try {
  25      const fetchResponse = await fetch(...args);
  26  
  27      let body: T | undefined;
  28      if (fetchResponse.status !== 204) {
  29        try {
  30          body = await fetchResponse.json();
  31        } catch (error) {
  32          console.error(error);
  33        }
  34      }
  35  
  36      if (!fetchResponse.ok) {
  37        throw new Error(
  38          fetchResponse.status +
  39            " " +
  40            ((body as ErrorResponse)?.message || "Unknown error")
  41        );
  42      }
  43      return body;
  44    } catch (error) {
  45      console.error("Failed to fetch", error);
  46      throw error;
  47    }
  48  };
  49