SetShippingMethod
Implements SetShippingMethod
Unified Method.
Source
import { defineApi, getCartId, query } from "@vsf-enterprise/unified-api-magento";
import type { Cart } from "@vsf-enterprise/unified-api-magento/ecommerceTypes";
import { getNormalizers } from "@vsf-enterprise/unified-api-magento/udl";
export const setShippingMethod = defineApi.setShippingMethod(async (context, args) => {
const cartId = getCartId(context);
const { carrier_code, method_code } = unwrapShippingMethodId(args.shippingMethodId);
const updatedCart = await query(
context.api.setShippingMethodsOnCart({
cart_id: cartId,
shipping_methods: [
{
carrier_code,
method_code,
},
],
}),
);
const { normalizeCart } = getNormalizers(context);
return normalizeCart(updatedCart.setShippingMethodsOnCart?.cart as Cart);
});
function unwrapShippingMethodId(input: string) {
const [carrier_code, method_code] = input.split(":");
if (!carrier_code || !method_code) {
throw new Error(
`Invalid shipping method id "${input}", expected a string in the format "carrier_code:method_code"`,
);
}
return { carrier_code, method_code };
}