async function breakdownQuery()

in grid-bridge-lambda/src/index.ts [81:125]


async function breakdownQuery(
  q: string | null
): Promise<GridSearchQueryBreakdown | null> {
  if (!q) return null;

  const collections = await Promise.all(
    [...q.matchAll(COLLECTIONS)].map(async (match) => {
      const text = match[1] ?? match[2] ?? match[3];
      const collectionResponse = await gridFetch(
        `https://${collectionsDomain}/collections/${text}`
      );

      if (!isCollectionResponse(collectionResponse)) {
        throw new Error("Fetching collection response failed to parse");
      }
      return {
        text: collectionResponse.data.fullPath.join("/"),
        color: collectionResponse.data.cssColour ?? "#555",
      };
    })
  );
  const notCollections = q.replace(COLLECTIONS, "");

  const labels = [...notCollections.matchAll(LABELS)].map((match) => ({
    text: match[1] ?? match[2] ?? match[3],
    color: "#00adee",
  }));
  const notLabels = notCollections.replace(LABELS, "");

  const chips = [...notLabels.matchAll(CHIPS)].map((match) => ({
    text: match[1] + ":" + (match[2] ?? match[3] ?? match[4]),
    color: "#333333",
  }));
  const notChips = notLabels.replace(CHIPS, "");

  // flatten any remaining sequence of spaces into a single
  const restOfSearch = notChips.replace(/ {2,}/g, " ").trim();

  return {
    collections,
    labels,
    chips,
    restOfSearch,
  };
}