All files / src/services/api Api.tsx

97.5% Statements 39/40
88.63% Branches 39/44
94.11% Functions 16/17
100% Lines 32/32

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                  583x 578x   5x 10x     5x   5x   5x 13x 5x 5x 13x 5x             7x 4x 5x   4x                           81798x 81798x 81798x                                           3222x 3222x                                     3172x 3172x       3172x 3172x 732x 581x                       2646x               315x               11x               74x             120x      
import axios, { AxiosRequestConfig, AxiosResponse } from "axios";
 
/**
 * A call's params laid over the defaults. Either side may be a plain object
 * or a `URLSearchParams` — the form a repeated key (`?agent_id=a&agent_id=b`)
 * needs. Spreading a `URLSearchParams` gives `{}`, which silently dropped
 * every param a network tile sent; a call's key replaces the default's.
 */
export function mergeParams(base: unknown, own: unknown): unknown {
  if (!(own instanceof URLSearchParams) && !(base instanceof URLSearchParams)) {
    return { ...((base as object) ?? {}), ...((own as object) ?? {}) };
  }
  const entries = (value: unknown): [string, string][] =>
    value instanceof URLSearchParams
      ? [...value.entries()]
      : Object.entries((value as Record<string, unknown>) ?? {})
          .filter(([, v]) => v !== undefined && v !== null)
          .flatMap(([k, v]) =>
            Array.isArray(v) ? v.map((x) => [k, String(x)] as [string, string]) : [[k, String(v)] as [string, string]],
          );
  const mine = entries(own);
  const overridden = new Set(mine.map(([k]) => k));
  const merged = new URLSearchParams();
  for (const [k, v] of entries(base)) if (!overridden.has(k)) merged.append(k, v);
  for (const [k, v] of mine) merged.append(k, v);
  return merged;
}
 
/** `config` with no `Content-Type` header, under any capitalisation. */
function withoutContentType(
  config: AxiosRequestConfig | undefined,
): AxiosRequestConfig | undefined {
  if (!config?.headers) return config;
  const headers = Object.fromEntries(
    Object.entries(config.headers).filter(([k]) => k.toLowerCase() !== "content-type"),
  );
  return { ...config, headers } as AxiosRequestConfig;
}
 
export class API {
  /** Base URL. Empty means same-origin relative requests. */
  host: string;
  token: string | null;
  default_config: AxiosRequestConfig | null;
 
  constructor(
    host: string | undefined,
    token: string | null = null,
    default_config: AxiosRequestConfig | null = null,
  ) {
    this.host = host ?? "";
    this.token = token;
    this.default_config = default_config;
  }
 
  /**
   * Absolute URL for `route`, or a same-origin relative one when no host is
   * configured.
   *
   * `host` comes from `import.meta.env.VITE_API_URL`, which is `string |
   * undefined` however this field is typed — `.env` is gitignored, so the
   * variable is simply absent in CI and in a fresh checkout. Reading
   * `.replace` off `undefined` there threw a `TypeError` from inside
   * whichever router was called, *before* the request was made: every query
   * rejected with a message naming neither the endpoint nor the missing
   * variable, and a page whose data silently never arrived looked like a
   * backend outage.
   *
   * An empty host yields `/rules/catalogue`, a coherent same-origin request —
   * a real deployment shape here, not a fiction: fe-core is served from the
   * same nginx vhost that proxies `/api/*`, which is exactly what
   * `.env.standalone` configures with a relative `VITE_API_URL`.
   */
  endpoint(route: string) {
    const host = (this.host ?? "").replace(/\/+$/, "");
    return `${host}/${route.replace(/^\/+/, "")}`;
  }
 
  /**
   * The defaults with a call's own config laid over them. `params` and
   * `headers` merge key by key, so a call that passes `{ params }` keeps the
   * default headers, credentials and params (the workspace among them)
   * rather than replacing them — which it used to.
   *
   * A `FormData` body goes without a `Content-Type`. The defaults say
   * `application/json`, and axios sends a FormData under that header as
   * JSON (`{"file":{}}`), so every upload since headers merged reached
   * svc-core with no file and was refused with a 422. Without one, the
   * browser writes the multipart body and its boundary.
   */
  config(
    config: AxiosRequestConfig | null = null,
    body?: unknown,
  ): AxiosRequestConfig | undefined {
    const merged = this.merged(config);
    return body instanceof FormData ? withoutContentType(merged) : merged;
  }
 
  private merged(config: AxiosRequestConfig | null): AxiosRequestConfig | undefined {
    const base = this.default_config;
    if (!config) return base ?? undefined;
    if (!base) return config;
    return {
      ...base,
      ...config,
      params: mergeParams(base.params, config.params),
      headers: { ...(base.headers ?? {}), ...(config.headers ?? {}) },
    } as AxiosRequestConfig;
  }
 
  async get<T>(
    route: string,
    config: AxiosRequestConfig | null = null,
  ): Promise<AxiosResponse<T>> {
    return axios.get<T>(this.endpoint(route), this.config(config));
  }
 
  async post<T>(
    route: string,
    data: unknown,
    config: AxiosRequestConfig | null = null,
  ): Promise<AxiosResponse<T>> {
    return axios.post<T>(this.endpoint(route), data, this.config(config, data));
  }
 
  async put<T>(
    route: string,
    data: unknown,
    config: AxiosRequestConfig | null = null,
  ): Promise<AxiosResponse<T>> {
    return axios.put<T>(this.endpoint(route), data, this.config(config, data));
  }
 
  async patch<T>(
    route: string,
    data: unknown,
    config: AxiosRequestConfig | null = null,
  ): Promise<AxiosResponse<T>> {
    return axios.patch<T>(this.endpoint(route), data, this.config(config, data));
  }
 
  async delete<T>(
    route: string,
    config: AxiosRequestConfig | null = null,
  ): Promise<AxiosResponse<T>> {
    return axios.delete<T>(this.endpoint(route), this.config(config));
  }
}