GetAvailableShippingMethods
Implements GetAvailableShippingMethods
Unified Method.
Source
import type { Context } from "@vue-storefront/magento-api";
import { defineApi, getCartId, query } from "@vsf-enterprise/unified-api-magento";
import type { NormalizersTypes } from "@vsf-enterprise/unified-api-magento";
import { getNormalizers } from "@vsf-enterprise/unified-api-magento/udl";
export const getAvailableShippingMethods = defineApi.getAvailableShippingMethods(
async (context) => {
const customerToken = context.config.state.getCustomerToken();
const getShippingMethodsPromise = customerToken
? getCustomerShippingMethods
: getGuestShippingMethods;
const shippingMethods = await getShippingMethodsPromise(context);
if (shippingMethods.length === 0) {
throw new Error("No shipping methods available");
}
const { normalizeShippingMethod } = getNormalizers(context);
return {
methods:
shippingMethods
.map((method) =>
normalizeShippingMethod(method as NormalizersTypes.NormalizeShippingMethodInput),
)
.filter(Boolean) || [],
};
},
);
async function getCustomerShippingMethods(context: Context) {
const data = await query(context.api.getAvailableCustomerShippingMethods());
return data?.customerCart?.shipping_addresses?.[0]?.available_shipping_methods ?? [];
}
async function getGuestShippingMethods(context: Context) {
const cartId = getCartId(context);
const data = await query(context.api.getAvailableShippingMethods({ cart_id: cartId }));
return data?.cart?.shipping_addresses?.[0]?.available_shipping_methods || [];
}