🚧 Switch to swell-js to handle Shop cart

swell-node was relying too much on Node packages like crypto or events to be used with Cloudflare Pages or Vercel Edge Functions
This commit is contained in:
2022-09-18 12:11:44 +02:00
parent b3fdc5cea5
commit b66db25942
12 changed files with 210 additions and 351 deletions

View File

@@ -1,34 +1,99 @@
import swell from 'swell-js'
import { addNotification } from '$utils/functions/notifications'
import { cartData } from '$utils/stores/shop'
import { PUBLIC_SWELL_STORE_ID, PUBLIC_SWELL_API_PUBLIC_TOKEN } from '$env/static/public'
// Init Swell
export const initSwell = () => {
swell.init(PUBLIC_SWELL_STORE_ID, PUBLIC_SWELL_API_PUBLIC_TOKEN)
}
/**
* Get current cart
*/
export const getCart = async () => {
const cart = await swell.cart.get()
if (cart) {
return cart
}
}
/**
* Add a product to a cart
*/
export const addToCart = async (cartId: string, product: any, quantity: number = 1) => {
if (cartId && cartId !== 'null') {
const updatedCart = await fetch('/api/swell', {
method: 'POST',
body: JSON.stringify({
action: 'addToCart',
cartId,
productId: product.id,
quantity,
})
export const addToCart = async (product: any, quantity: number = 1) => {
const updatedCart = await swell.cart.addItem({
product_id: product.id,
quantity,
})
if (updatedCart) {
// Update cart data
cartData.set(updatedCart)
// Show notification
addNotification({
title: 'Added to cart',
name: `${product.name} - x1`,
image: product.images[0].file.url,
})
}
}
if (updatedCart.ok) {
const newCart = await updatedCart.json()
cartData.set(newCart)
/**
* Update Cart item
*/
export const updateCartItem = async (productId: string, quantity: number) => {
const updatedCart = await swell.cart.updateItem(productId, {
quantity,
})
// Show notification
addNotification({
title: 'Added to cart',
name: `${product.name} - x1`,
image: product.images[0].file.url,
})
}
} else {
console.log('No active cart')
if (updatedCart) {
return updatedCart
}
}
/**
* Remove Cart item
*/
export const removeCartItem = async (productId: string) => {
const updatedCart = await swell.cart.removeItem(productId)
if (updatedCart) {
return updatedCart
}
}
/**
* Fetch products
*/
export const getProducts = async (category?: string, limit: number = 25, page: number = 1) => {
const products = await swell.products.list({
where: {
active: true,
},
category,
limit,
page
})
if (products) {
return products
}
}
/**
* Retrieve a product
*/
export const getProduct = async (id: string) => {
const product = await swell.products.get(id)
if (product) {
return product
}
}