All files / react-app/src/api useGetItem.ts

98.33% Statements 59/60
92.98% Branches 53/57
100% Functions 11/11
98.3% Lines 58/59

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                      108x   108x 1236x   108x 5821x 5821x     108x           69143x 20474x     48669x 48669x   48669x 35904x     12765x 67889x 67889x           12765x     108x 1254x                                         1254x       1254x 1254x 48669x   1254x               4885x       108x       1254x 1254x       1254x 1254x               483x 19x     464x   771x 767x     4x 4x 1x     3x       108x 905x 905x 241x     664x 663x   1x 1x       108x 590x 590x 205x     385x 384x   1x 1x       108x         880x                   9x        
import { useQuery, UseQueryOptions } from "@tanstack/react-query";
import { API } from "aws-amplify";
import { opensearch, ReactQueryApiError, SEATOOL_STATUS } from "shared-types";
 
import { sendGAEvent } from "@/utils/ReactGA/SendGAEvent";
 
type GetItemOptions = {
  includeDraft?: boolean;
  preferDraft?: boolean;
};
 
const ITEM_NOT_FOUND_MESSAGE = "No record found for the given id";
 
const includesNotFoundMessage = (value: unknown) =>
  String(value ?? "").includes(ITEM_NOT_FOUND_MESSAGE);
 
const normalizeStatusCode = (value: unknown) => {
  const statusCode = typeof value === "string" ? Number(value) : value;
  return typeof statusCode === "number" && Number.isFinite(statusCode) ? statusCode : undefined;
};
 
const collectErrorValues = (
  value: unknown,
  values: unknown[] = [],
  seen = new Set<unknown>(),
  depth = 0,
) => {
  if (value === null || value === undefined || depth > 4 || seen.has(value)) {
    return values;
  }
 
  seen.add(value);
  values.push(value);
 
  if (typeof value !== "object") {
    return values;
  }
 
  for (const key of Object.getOwnPropertyNames(value)) {
    try {
      collectErrorValues((value as Record<string, unknown>)[key], values, seen, depth + 1);
    } catch {
      // Some Error-like objects have getters that can throw.
    }
  }
 
  return values;
};
 
const isNotFoundItemPayload = (value: unknown): boolean => {
  const candidate = value as {
    found?: boolean;
    message?: unknown;
    _source?: unknown;
    request?: {
      status?: number;
    };
    response?: {
      status?: number;
      statusCode?: number;
      statusText?: string;
      data?: unknown;
    };
    $metadata?: {
      httpStatusCode?: number;
    };
    status?: number;
    statusCode?: number;
  };
 
  const responseStatus =
    candidate?.response?.status ??
    candidate?.response?.statusCode ??
    candidate?.request?.status ??
    candidate?.$metadata?.httpStatusCode;
  const directStatus = candidate?.status ?? candidate?.statusCode;
  const errorValues = collectErrorValues(value);
  const errorText = errorValues.map((errorValue) => String(errorValue ?? "")).join(" ");
 
  return (
    candidate?.found === false ||
    includesNotFoundMessage(errorText) ||
    /status code 404/i.test(errorText) ||
    /\b404\b/i.test(errorText) ||
    /not found/i.test(errorText) ||
    normalizeStatusCode(responseStatus) === 404 ||
    normalizeStatusCode(directStatus) === 404 ||
    errorValues.some((errorValue) => normalizeStatusCode(errorValue) === 404)
  );
};
 
export const getItem = async (
  id: string,
  options?: GetItemOptions,
): Promise<opensearch.main.ItemResult | undefined> => {
  const normalizedId = id?.trim().toUpperCase();
  Iif (!normalizedId) {
    return undefined;
  }
 
  try {
    const response = await API.post("os", "/item", {
      body: {
        id: normalizedId,
        includeDraft: options?.includeDraft,
        preferDraft: options?.preferDraft,
      },
    });
 
    if (isNotFoundItemPayload(response) || !(response as opensearch.main.ItemResult)?._source) {
      return undefined;
    }
 
    return response;
  } catch (error) {
    if (isNotFoundItemPayload(error)) {
      return undefined;
    }
 
    sendGAEvent("api_error", { message: `failure /item ${normalizedId}` });
    if (options?.includeDraft && options.preferDraft) {
      return undefined;
    }
 
    throw error;
  }
};
 
export const idIsApproved = async (id: string) => {
  try {
    if (!id?.trim()) {
      return false;
    }
 
    const record = await getItem(id);
    return record?._source?.seatoolStatus == SEATOOL_STATUS.APPROVED;
  } catch (e) {
    console.error(e);
    return false;
  }
};
 
export const canBeRenewedOrAmended = async (id: string) => {
  try {
    if (!id?.trim()) {
      return false;
    }
 
    const record = await getItem(id);
    return ["New", "Renew"].includes(record?._source?.actionType ?? "");
  } catch (e) {
    console.error(e);
    return false;
  }
};
 
export const useGetItem = (
  id: string,
  options?: UseQueryOptions<opensearch.main.ItemResult | undefined, ReactQueryApiError>,
  requestOptions?: GetItemOptions,
) => {
  return useQuery<opensearch.main.ItemResult | undefined, ReactQueryApiError>(
    [
      "record",
      id,
      requestOptions?.includeDraft
        ? requestOptions?.preferDraft
          ? "preferDraft"
          : "includeDraft"
        : "mainOnly",
    ],
    () => getItem(id, requestOptions),
    options,
  );
};