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

Refactor extractPricingEntitiesBySlug #139

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
55 changes: 27 additions & 28 deletions src/pricing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,39 +159,38 @@ const getPriceComponents = (priceItem: CompositePriceItemDto): PriceComponent[]
* @returns the product and price relations from the price items grouped by their slug.
*/
export const extractPricingEntitiesBySlug = (
priceItems?: (PriceItem | CompositePriceItem)[],
priceItems: Array<PriceItem | CompositePriceItem> = [],
): PricingEntitiesExtractResult => {
const productRelations = [] as RelationAttributeValue['$relation'];
const priceRelations = [] as RelationAttributeValue['$relation'];
const priceLookup: Record<string, boolean> = {};
const productLookup: Record<string, boolean> = {};
const pricingTags: string[] = [];

priceItems?.forEach((item) => {
if (item?.product_id && !productLookup[item.product_id]) {
productRelations.push({
entity_id: item.product_id,
_schema: 'product',
_tags: [],
});
pricingTags.push(...(item._product?._tags || []));
productLookup[item.product_id] = true;
const productSet = new Set<string>();
const priceSet = new Set<string>();
const tagSet = new Set<string>();

for (const item of priceItems) {
/**
* Account for possibility that function might be called with
* array containing nullish items, even though it's typed not to
*/
if (!item) continue;

if (item.product_id) productSet.add(item.product_id);
if (item.price_id) priceSet.add(item.price_id);

const productTags = item._product?._tags?.filter(Boolean);
const priceTags = item._price?._tags?.filter(Boolean);

for (const tag of productTags ?? []) {
tagSet.add(tag);
}
if (item?.price_id && !priceLookup[item.price_id]) {
priceRelations.push({
entity_id: item.price_id,
_schema: 'price',
_tags: [],
});
pricingTags.push(...(item._price?._tags || []));
priceLookup[item.price_id] = true;

for (const tag of priceTags ?? []) {
tagSet.add(tag);
}
});
}

return {
product: { $relation: productRelations },
price: { $relation: priceRelations },
_tags: [...new Set(pricingTags)],
product: { $relation: Array.from(productSet).map((id) => ({ entity_id: id, _schema: 'product', _tags: [] })) },
price: { $relation: Array.from(priceSet).map((id) => ({ entity_id: id, _schema: 'price', _tags: [] })) },
_tags: Array.from(tagSet),
};
};

Expand Down
Loading