All files / js fetch.ts

0% Statements 0/18
0% Branches 0/10
0% Functions 0/5
0% Lines 0/17

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                                                                                                         
class FetchError extends Error {
  constructor(readonly code: string) {
    super();
  }
}
 
function handleJSON(response: Response) {
  if (!response.ok) {
    throw new FetchError("REQUEST_FAILED");
  }
  return response.json();
}
 
function paramsToQueryString(params: Record<string, string | null>) {
  const urlParams = new URLSearchParams();
  Object.entries(params).forEach(([key, value]) => {
    if (value !== null) {
      urlParams.set(key, value);
    }
  });
  return urlParams.toString();
}
 
/**
 * Load data from the JSON API.
 * @param url - The API endpoint to fetch
 * @param  params - URL params to set.
 * @param options - Additional fetch options, like the HTTP method.
 *                  If this contains a `json` key, that will be encoded to JSON
 *                  and sent as a request with the appropriate content type.
 */
 
export function loadData(
  url: string,
  params: Record<string, string | null> | null,
  options?: any
) {
  const apiUrl = `${$LEKTOR_CONFIG.admin_root}/api${url}`;
  const fetchUrl = params ? `${apiUrl}?${paramsToQueryString(params)}` : apiUrl;
 
  if (options && options.json !== undefined) {
    options.body = JSON.stringify(options.json);
    options.headers = { "Content-Type": "application/json" };
    delete options.json;
  }
 
  return fetch(fetchUrl, {
    credentials: "same-origin",
    method: "GET",
    ...options,
  }).then(handleJSON);
}