Skip to content

Commit

Permalink
fix: change related products promise type (#878)
Browse files Browse the repository at this point in the history
* fix: change related produts promise type

* chore: add error handling for one and all products

---------

Co-authored-by: Lucas Porto <[email protected]>
  • Loading branch information
portolucas and Lucas Porto authored Oct 3, 2024
1 parent 29b95e5 commit 0663326
Showing 1 changed file with 28 additions and 4 deletions.
32 changes: 28 additions & 4 deletions vtex/loaders/legacy/relatedProductsLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,14 +102,38 @@ async function loader(

/** Batch fetches due to VTEX API limits */
const batchedIds = batch(relatedIds, 50);
const relatedProducts = await Promise.all(

const relatedProductsResults = await Promise.allSettled(
batchedIds.map((ids) =>
productList({ props: { similars: false, ids } }, req, ctx)
),
).then((p) => p.flat().filter((x): x is Product => Boolean(x)));
);

const relatedProducts = relatedProductsResults
.filter(
(result): result is PromiseFulfilledResult<Product[]> =>
result.status === "fulfilled",
)
.flatMap((result) => result.value)
.filter((x): x is Product => Boolean(x));

relatedProductsResults
.filter((result) => result.status === "rejected")
.forEach((result, index) => {
console.error(
`Error loading related products for batch ${index}:`,
(result as PromiseRejectedResult).reason,
);
});

const allPromisesFailed = relatedProductsResults.every(
(result) => result.status === "rejected",
);

if (allPromisesFailed) {
throw new Error("Failed to load related products for all batches.");
}

// Search API does not offer a way to filter out in stock products
// This is a scape hatch
if (hideUnavailableItems && relatedProducts) {
const inStock = (p: Product) =>
p.offers?.offers.find((o) =>
Expand Down

0 comments on commit 0663326

Please sign in to comment.