async function buildPayloadFor()

in grid-bridge-lambda/src/index.ts [127:181]


async function buildPayloadFor(gridUrl: URL): Promise<PayloadAndType | null> {
  if (gridUrl.pathname === "/search") {
    const apiUrl = new URL(gridUrl.href);
    apiUrl.hostname = mediaApiDomain;
    apiUrl.pathname = apiUrl.pathname.replace("/search", "/images");
    apiUrl.searchParams.set("countAll", "true");
    apiUrl.searchParams.set("length", "0");
    const query = gridUrl.searchParams.get("query");
    if (query) {
      apiUrl.searchParams.set("q", query);
      apiUrl.searchParams.delete("query");
    }

    const embeddableUrl = new URL(gridUrl.href);
    embeddableUrl.searchParams.set("nonFree", "true");
    return {
      type: "grid-search",
      payload: {
        apiUrl: apiUrl.href,
        embeddableUrl: embeddableUrl.href,
      },
    };
  }
  if (gridUrl.pathname.startsWith("/images/")) {
    const maybeCrop = gridUrl.searchParams.get("crop");
    const apiUrl = new URL(gridUrl.href);
    apiUrl.hostname = mediaApiDomain;
    const imageResponse = (await gridFetch(apiUrl.href)) as {
      data: {
        thumbnail: { secureUrl: string };
        exports: Array<{
          id: string;
          assets: Array<{
            secureUrl: string;
            size: number;
            dimensions: { height: number; width: number };
          }>;
        }>;
      };
    }; // TODO probably define this in types.ts
    const thumbnail: string = maybeCrop
      ? imageResponse.data.exports
          .find((_) => _.id === maybeCrop)!
          .assets.sort((a, b) => a.size - b.size)[0]!.secureUrl
      : imageResponse.data.thumbnail.secureUrl;
    return {
      type: maybeCrop ? "grid-crop" : "grid-original",
      payload: {
        embeddableUrl: gridUrl.href,
        thumbnail,
      },
    };
  }
  return null;
}