All files / lib/libs/api/package checkIdentifierUsage.ts

100% Statements 12/12
100% Branches 2/2
100% Functions 1/1
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 68                                11x 11x 11x     11x                                             11x   10x 8x 8x   8x           2x       1x   1x          
import * as os from "libs/opensearch-lib";
import { getDomainAndNamespace } from "libs/utils";
 
export interface IdentifierCheckResult {
  exists: boolean;
  origin?: string;
}
 
/**
 * Checks if an identifier (SPA ID, Waiver ID) exists in the main index with case-insensitive matching.
 * Returns whether the identifier exists and its origin system if found.
 *
 * @param identifier - The identifier to check (case-insensitive)
 * @returns Object with exists flag and origin system name if found
 */
export async function checkIdentifierUsage(identifier: string): Promise<IdentifierCheckResult> {
  try {
    const { domain, index } = getDomainAndNamespace("main");
    const normalizedIdentifier = identifier.trim();
 
    // Use an exact keyword lookup with case-insensitive matching.
    const query = {
      size: 1,
      query: {
        bool: {
          must: [
            {
              term: {
                "id.keyword": {
                  value: normalizedIdentifier,
                  case_insensitive: true,
                },
              },
            },
          ],
          must_not: [
            {
              term: { deleted: true },
            },
          ],
        },
      },
    };
 
    const results = await os.search(domain, index, query);
 
    if (results?.hits?.hits?.length > 0) {
      const document = results.hits.hits[0];
      const origin = document._source?.origin as string | undefined;
 
      return {
        exists: true,
        origin: origin,
      };
    }
 
    return {
      exists: false,
    };
  } catch (error) {
    console.error("Error checking identifier usage:", error);
    // Return false on error to be safe - external systems can retry
    return {
      exists: false,
    };
  }
}