All files / src/services/api ApiRouter.tsx

100% Statements 19/19
100% Branches 17/17
100% Functions 6/6
100% Lines 18/18

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              81786x                 81786x 81786x 81786x                                 2504x 2504x   148x       149x 201x 201x 1x   2x       200x 1x   199x             148x 148x       2763x      
import { AxiosRequestConfig, AxiosResponse } from "axios";
import { Dictionary } from "@/types/ext";
import { API } from "./Api";
 
export class APIRouter {
  api: API;
  prefix: string;
  headers: Dictionary<string> = {};
 
  constructor(
    prefix: string,
    host: string,
    token: string | null = null,
    default_config: AxiosRequestConfig<any> | null = null,
    headers: Dictionary<string> = {}
  ) {
    this.api = new API(host, token, default_config);
    this.prefix = prefix;
    this.headers = headers;
  }
 
  /**
   * A path under this router's prefix, with an optional query string.
   *
   * An empty `route` means the collection itself, and must NOT produce a
   * trailing slash. svc-core mounts its list endpoints at `""` — `@router
   * .get("")` — so `/app/reviews/` does not match and FastAPI answers 307 to
   * `/app/reviews`. That redirect is fatal rather than merely wasteful here:
   * svc-core builds the `Location` from the request it received, which behind
   * the proxy is its own internal host, and svc-bff forwards responses with
   * `follow_redirects=False`. The browser is handed a URL it cannot reach and
   * the request simply never resolves — which is exactly how the reviewer
   * queue failed to load.
   */
  endpoint(route: string, query?: Record<string, unknown>) {
    const path = route ? `${this.prefix}/${route}` : this.prefix;
    if (!query) return path;
 
    const buildQuery = (
      obj: Record<string, unknown>,
      prefix?: string
    ): string[] => {
      return Object.entries(obj).flatMap(([key, value]) => {
        const fullKey = prefix ? `${prefix}[${key}]` : key;
        if (Array.isArray(value)) {
          return value.map(
            (v) =>
              `${encodeURIComponent(fullKey)}[]=${encodeURIComponent(
                String(v)
              )}`
          );
        } else if (typeof value === "object" && value !== null) {
          return buildQuery(value as Record<string, unknown>, fullKey);
        } else {
          return `${encodeURIComponent(fullKey)}=${encodeURIComponent(
            String(value)
          )}`;
        }
      });
    };
 
    const qstr = buildQuery(query).join("&");
    return qstr ? `${path}?${qstr}` : path;
  }
 
  validRes(res: AxiosResponse<any, any>) {
    return res.status < 500;
  }
}