Move functions to directory

This commit is contained in:
2021-11-08 12:14:39 +01:00
parent 7242027be9
commit 5141198167
6 changed files with 41 additions and 1 deletions

View File

@@ -0,0 +1,137 @@
import swell from 'swell-node'
// Init Swell
swell.init(import.meta.env.VITE_SWELL_STORE_ID, import.meta.env.VITE_SWELL_API_TOKEN)
/**
* Retrieve a product
*/
export const getProduct = async (id: string) => {
const product = await swell.get('/products/{id}', {
id
})
if (product) {
return product
}
}
/**
* Create a cart
*/
export const createCart = async () => {
const cart = await swell.post('/carts')
if (cart) {
return cart
}
}
/**
* Retrieve cart
*/
export const fetchCart = async (id: string) => {
const cart = await swell.get('/carts/{id}', {
id,
expand: [
'items.product',
'items.variant',
]
})
if (cart) {
return cart
}
}
/**
* Add product to cart
*/
export const addToCart = async (cartId: string, productId: string, quantity: number) => {
// Fetch current cart data
const currentCart = await fetchCart(cartId)
// Updated cart with new items
const updatedCart = await swell.put('/carts/{id}', {
id: cartId,
items: [
...currentCart.items || [],
{
product_id: productId,
quantity,
}
],
})
if (updatedCart) {
// Fetch latest cart with updates
const cart = await fetchCart(cartId)
if (cart) {
return cart
}
}
}
/**
* Update cart item
*/
export const updateCartItem = async (cartId: string, productId: string, quantity: number) => {
// Fetch current cart data
const currentCart = await fetchCart(cartId)
// Updated items with replacing new item quantity
const updatedCartItems = currentCart.items.map((item: any) => {
// Replace item quantity with selected one
if (item.id === productId) {
item.quantity = quantity
}
return item
})
const updatedCart = await swell.put('/carts/{id}', {
id: cartId,
$set: {
items: updatedCartItems,
}
})
if (updatedCart) {
// Fetch latest cart with updates
const cart = await fetchCart(cartId)
if (cart) {
return cart
}
}
}
/**
* Remove cart item
*/
export const removeCartItem = async (cartId: string, productId: string) => {
// Fetch current cart data
const currentCart = await fetchCart(cartId)
// Updated items and remove selected item
const updatedCartItems = [...currentCart.items.filter((item: any) => {
return item.id !== productId
})]
const updatedCart = await swell.put('/carts/{id}', {
id: cartId,
$set: {
items: updatedCartItems,
}
})
if (updatedCart) {
// Fetch latest cart with updates
const cart = await fetchCart(cartId)
if (cart) {
return cart
}
}
}