All files / lib/lambda/submit getNextSplitSPAId.ts

100% Statements 11/11
75% Branches 3/4
100% Functions 2/2
100% Lines 11/11

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        1x 2x 2x                 2x       2x 1x 1x         2x 1x   1x   1x    
import { search } from "libs/opensearch-lib";
import { getDomainAndNamespace } from "libs/utils";
import { cpocs } from "lib/packages/shared-types/opensearch";
 
export const getNextSplitSPAId = async (spaId: string) => {
  const { domain, index } = getDomainAndNamespace("main");
  const query = {
    size: 50,
    query: {
      regexp: {
        "id.keyword": `${spaId}-[A-Z]`,
      },
    },
  };
  // Get existing split SPAs for this package id
  const { hits } = await search(domain, index, query);
  // Extract suffixes from existing split SPA IDs
  // If there are no split SPAs yet, start at the ASCII character before "A" ("@")
  // Convert to ASCII char codes to get latest suffix
  const latestSuffixCharCode = hits.hits.reduce((maxCharCode: number, hit: cpocs.ItemResult) => {
    const suffix = hit._source.id.toString().split("-").at(-1) ?? "@";
    return Math.max(maxCharCode, suffix.charCodeAt(0));
  }, "@".charCodeAt(0));
 
  // Increment letter but not past "Z"
  // "A-Z" is 65-90 in ASCII
  if (latestSuffixCharCode >= 90) {
    throw new Error("This package can't be further split.");
  }
  const nextSuffix = String.fromCharCode(latestSuffixCharCode + 1);
 
  return `${spaId}-${nextSuffix}`;
};