# All files / api client.js

100% Statements 12/12
83.33% Branches 15/18
100% Functions 4/4
100% Lines 12/12

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

    4x

    20x
    20x

    18x
    1x

    17x
    1x

    16x

    2x
    2x

    10x

    5x

     import { requestHttp } from "./http";

    function makeError(type, message, extra = {}) {
      return {
        type,
        message,
        ...extra,
      };
    }

    export async function apiRequest(method, path, body, options) {
      try {
        const { response, data, meta } = await requestHttp(method, path, body, options);

        if (!response.ok) {
          return {
            ok: false,
            error: makeError("http_error", `HTTP ${response.status}`, {
              statusCode: response.status,
              raw: data,
            }),
            meta,
          };
        }

        if (data && typeof data === "object" && (data.status === false || data.status === "error")) {
          return {
            ok: false,
            error: makeError("api_error", data.msg || data.message || "API error", {
              errorAlias: data.error_alias,
              failedFields: data.failed_fields || [],
              raw: data,
            }),
            meta,
          };
        }

        return {
          ok: true,
          data,
          meta,
        };
      } catch (error) {
        const isAbort = error?.name === "AbortError";
        return {
          ok: false,
          error: makeError(isAbort ? "timeout" : "network_error", error?.message || "Network error", {
            details: error,
          }),
          meta: {
            url: path,
            method,
            statusCode: 0,
            headers: null,
          },
        };
      }
    }

    export function apiGet(path, options) {
      return apiRequest("GET", path, null, options);
    }

    export function apiPost(path, body, options) {
      return apiRequest("POST", path, body, options);
    }