@scayle/storefront-core
Version:
Collection of essential utilities to work with the Storefront API
87 lines (86 loc) • 3.07 kB
JavaScript
import { ExistingItemHandling } from "@scayle/storefront-api";
import { decodeJwt } from "jose";
export const getValidatedAccessToken = (accessToken) => {
if (!accessToken) {
return;
}
const payload = decodeJwt(accessToken);
if (!payload.exp || payload.exp < Date.now() / 1e3) {
return;
}
return accessToken;
};
export const mergeBaskets = async (fromBasketKey, toBasketKey, withOptions, context) => {
const { sapiClient } = context;
const campaignKey = await context.callRpc?.("getCampaignKey");
const fromOriginBasket = await sapiClient.basket.get(fromBasketKey, {
with: withOptions,
campaignKey,
orderCustomData: withOptions.orderCustomData,
customerToken: getValidatedAccessToken(context.accessToken) ?? void 0
});
context.log.debug(`Merging basket ${fromBasketKey} to ${toBasketKey}`);
if (fromBasketKey === toBasketKey) {
return fromOriginBasket;
}
const { basket: fromBasket, type } = fromOriginBasket;
if (type === "success" && fromBasket?.items?.length > 0) {
const itemsToAddOrUpdate = fromBasket.items.map((item) => ({
variantId: item.variant.id,
quantity: item.quantity,
params: {
promotions: item.promotions,
customData: item.customData,
displayData: item.displayData,
itemGroup: item.itemGroup,
pricePromotionKey: withOptions.pricePromotionKey
}
}));
const mergedBasket = await sapiClient.basket.addOrUpdateItems(
toBasketKey,
itemsToAddOrUpdate,
{
with: withOptions,
campaignKey,
includeItemsWithoutProductData: withOptions?.includeItemsWithoutProductData,
orderCustomData: withOptions.orderCustomData,
customerToken: getValidatedAccessToken(context.accessToken) ?? void 0
},
{
existingItemHandling: ExistingItemHandling.ADD_QUANTITY_TO_EXISTING
}
);
fromBasket.items.map(async (item) => {
return await sapiClient.basket.deleteItem(fromBasketKey, item.key);
});
return mergedBasket;
}
};
export const mergeWishlists = async (fromWishlistKey, toWishlistKey, withOptions, context) => {
const { sapiClient } = context;
const campaignKey = await context.callRpc?.("getCampaignKey");
const oldWishlist = await sapiClient.wishlist.get(fromWishlistKey, {
with: withOptions,
campaignKey
});
context.log.debug(`Merging wishlist ${fromWishlistKey} to ${toWishlistKey}`);
if (oldWishlist != null) {
for (const item of oldWishlist.items) {
const { productId, variantId } = item;
if (productId || variantId) {
await sapiClient.wishlist.addItem(
toWishlistKey,
{
...variantId ? { variantId } : { productId }
},
{
campaignKey,
...item.itemGroup ? { itemGroup: item.itemGroup } : void 0,
...item.customData && Object.keys(item.customData).length ? { customData: item.customData } : void 0
}
);
sapiClient.wishlist.deleteItem(fromWishlistKey, item?.key);
}
}
}
};