-
Notifications
You must be signed in to change notification settings - Fork 0
/
useCart.js
66 lines (61 loc) · 1.75 KB
/
useCart.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import Client from 'shopify-buy'
const config = useRuntimeConfig()
const shopifyClient = Client.buildClient({
domain: config.public.shopifyDomain,
storefrontAccessToken: config.public.shopifyToken,
})
const cart = ref({})
const cartId = ref({})
export default function useCart() {
const assignCheckoutData = (fetchedCheckout) => {
const checkout = {}
const items = []
let itemCount = 0
fetchedCheckout.lineItems.forEach((item) => {
itemCount = itemCount + parseInt(item.quantity)
items.push({
title: item.title,
quantity: item.quantity,
price: Math.floor(item.variant?.priceV2?.amount),
})
})
checkout.quantity = itemCount
checkout.id = fetchedCheckout.id
checkout.items = items
checkout.total = Math.floor(fetchedCheckout.totalPriceV2?.amount)
checkout.currency = fetchedCheckout.currencyCode
return checkout
}
async function getCart(existingCartId) {
if (existingCartId) {
shopifyClient.checkout.fetch(existingCartId).then((fetchedCheckout) => {
cartId.value = fetchedCheckout.id
cart.value = assignCheckoutData(fetchedCheckout)
})
} else {
shopifyClient.checkout.create().then((fetchedCheckout) => {
cartId.value = fetchedCheckout.id
cart.value = assignCheckoutData(fetchedCheckout)
})
}
}
async function addToCart(variantId) {
const itemsToAdd = [
{
variantId,
quantity: 1,
},
]
shopifyClient.checkout
.addLineItems(cartId.value, itemsToAdd)
.then((fetchedCheckout) => {
cart.value = assignCheckoutData(fetchedCheckout)
})
}
return {
cart: computed(() => cart.value),
cartId: computed(() => cartId.value),
addToCart,
getCart,
}
}