Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: change related products promise type #878

Merged
merged 2 commits into from
Oct 3, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading