All files / client/src/utils api.ts

67.79% Statements 40/59
52.94% Branches 9/17
100% Functions 11/11
68.96% Lines 40/58

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181                        357x 357x 357x 357x 357x 357x                         357x   357x                           357x 357x   357x       357x     357x                         357x         2140x       2140x 2140x 1773x       2140x 2140x     2140x 2140x                     2128x           2128x   30x 30x       30x   30x       2098x                                         2098x 2098x 2095x               357x           658x               1473x 1473x 315x 315x   1473x               9x      
import { t } from "i18next";
import { config } from "shared/config";
import { getJWT } from "client/utils/getJWT";
import { addError } from "client/views/admin/adminSlice";
import {
  ApiDevEndpoint,
  ApiEndpoint,
  AuthEndpoint,
} from "shared/constants/apiEndpoints";
import { ApiError } from "shared/types/api/errors";
import { store } from "client/utils/store";
 
export enum BackendErrorType {
  NETWORK_ERROR = "backendError.networkError",
  API_ERROR = "backendError.apiError",
  UNAUTHORIZED = "backendError.unauthorized",
  INVALID_REQUEST = "backendError.invalidRequest",
  UNKNOWN = "backendError.unknown",
}
 
enum HttpMethod {
  GET = "GET",
  POST = "POST",
  DELETE = "DELETE",
}
 
interface ApiResponse<T> {
  data: T;
}
 
const baseURL = config.client().apiServerUrl;
 
const getErrorReason = (status: number): BackendErrorType => {
  switch (status) {
    case 401:
      return BackendErrorType.UNAUTHORIZED;
    case 422:
      return BackendErrorType.INVALID_REQUEST;
    default:
      return BackendErrorType.UNKNOWN;
  }
};
 
// Requests failing around a connectivity change are expected (e.g. laptop
// wakes from sleep and polls before Wi-Fi has reconnected), so the network
// error toast is suppressed while offline and briefly after reconnecting
const RECONNECT_GRACE_PERIOD_MS = 5000;
let reconnectedAt = 0;
 
addEventListener("online", () => {
  reconnectedAt = Date.now();
});
 
const shouldShowNetworkError = (): boolean =>
  navigator.onLine && Date.now() - reconnectedAt > RECONNECT_GRACE_PERIOD_MS;
 
const networkErrorResponse = <T>(): ApiResponse<T> => {
  if (shouldShowNetworkError()) {
    store.dispatch(addError(t(BackendErrorType.NETWORK_ERROR)));
  }
 
  const error: ApiError = {
    errorId: "unknown",
    message: "Network error",
    status: "error",
  };
  return { data: error as T };
};
 
const apiFetch = async <T>(
  url: string,
  method: HttpMethod,
  body?: unknown,
): Promise<ApiResponse<T>> => {
  const headers: Record<string, string> = {
    "Content-Type": "application/json",
  };
 
  const authToken = getJWT();
  if (authToken) {
    headers.Authorization = `Bearer ${authToken}`;
  }
 
  // Change to AbortSignal.timeout() at some point when browsers mature more
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), 60000);
 
  let response: Response;
  try {
    response = await fetch(`${baseURL}${url}`, {
      method,
      headers,
      body: body === undefined ? undefined : JSON.stringify(body),
      signal: controller.signal,
    });
  } catch {
    clearTimeout(timeoutId);
    return networkErrorResponse<T>();
  }
 
  clearTimeout(timeoutId);
 
  // Reading the response body can reject with AbortError if the page unloads
  // mid-response, so json() calls need the same error handling as fetch()
 
  // Handle redirect responses (301/302 with JSON body containing location)
  if ([301, 302].includes(response.status)) {
    let data: { location: string };
    try {
      data = (await response.json()) as { location: string };
    } catch {
      return networkErrorResponse<T>();
    }
    location.href = data.location;
    // eslint-disable-next-line @typescript-eslint/no-empty-function
    return new Promise<ApiResponse<T>>(() => {});
  }
 
  // Handle errors
  Iif (!response.ok) {
    const errorReason = getErrorReason(response.status);
 
    store.dispatch(
      addError(
        t(BackendErrorType.API_ERROR, {
          method,
          url,
          errorReason: t(errorReason),
        }),
      ),
    );
 
    const error: ApiError = {
      errorId: "unknown",
      message: "Invalid API response",
      status: "error",
    };
    return { data: error as T };
  }
 
  try {
    const data = (await response.json()) as T;
    return { data };
  } catch {
    return networkErrorResponse<T>();
  }
};
 
type Endpoint = ApiEndpoint | ApiDevEndpoint | AuthEndpoint;
 
export const api = {
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
  post: async <RES = never, REQ = never>(
    url: Endpoint,
    data?: REQ,
  ): Promise<ApiResponse<RES>> => {
    return await apiFetch<RES>(url, HttpMethod.POST, data);
  },
 
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
  get: async <RES = never, REQ = never>(
    url: Endpoint,
    options?: { params?: REQ },
  ): Promise<ApiResponse<RES>> => {
    let fetchUrl: string = url;
    if (options?.params) {
      const searchParams = new URLSearchParams(options.params);
      fetchUrl = `${url}?${searchParams.toString()}`;
    }
    return await apiFetch<RES>(fetchUrl, HttpMethod.GET);
  },
 
  // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
  delete: async <RES = never, REQ = never>(
    url: Endpoint,
    options?: { data?: REQ },
  ): Promise<ApiResponse<RES>> => {
    return await apiFetch<RES>(url, HttpMethod.DELETE, options?.data);
  },
};