[wip] 🔥 Integrate Swell into the shop

Create a custom and internal API for fetching and updating content to Swell Admin API (using swell-node)
This commit is contained in:
2021-11-07 11:51:01 +01:00
parent 2f043af38e
commit bd74f5612c
14 changed files with 543 additions and 148 deletions

View File

@@ -1,5 +1,27 @@
import { writable } from 'svelte/store'
import { writable, derived } from 'svelte/store'
// Shop
export const cartOpen = writable(false)
export const cartAmount = writable(3)
/**
* Shop
*/
/** Open Cart state */
export const cartOpen = writable(true)
/** Current Cart ID */
export const cartId = writable(null)
if (typeof localStorage !== 'undefined') {
if (localStorage.getItem('cartId')) {
console.log('existant', localStorage.getItem('cartId'))
cartId.set(localStorage.getItem('cartId'))
}
cartId.subscribe(value => localStorage.setItem('cartId', value))
}
/** Raw Cart data */
export const cartData = writable(null)
/** Amount of products present in cart */
export const cartAmount = derived(cartData, ($cart) => {
return $cart && $cart.item_quantity > 0 ? $cart.item_quantity : 0
})

102
src/utils/swellFunctions.ts Normal file
View File

@@ -0,0 +1,102 @@
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}`)
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 (cartId: string) => {
const cart = await swell.get('/carts/{id}', {
id: cartId,
expand: [
'items.product',
'items.variant',
]
})
if (cart) {
return cart
}
}
/**
* Add product to cart
*/
export const addToCart = async (cartId: string, productId: string, quantity: number) => {
// TODO: Update current product quantity if adding again, otherwise add new product to existing items
const updatedCart = await swell.put('/carts/{id}', {
id: cartId,
items: [{
product_id: productId,
quantity: quantity,
expand: [
'items.product',
'items.variant',
]
}],
})
if (updatedCart) {
return updatedCart
}
}
/**
* Update cart item
*/
export const updateCartItem = async (cartId: string, productId: string, quantity: number) => {
// Fetch current cart data
const currentCart = await fetchCart(cartId)
// Update cart
// const itemToUpdate = currentCart.items.find((item: any) => item.id === productId)
// itemToUpdate.quantity = quantity
// Updated items with replacing new item quantity
const updatedCartItems = currentCart.items.map((item: any) => {
console.log(item)
return item
})
// const updatedCart = await swell.put('/carts/{id}', {
// id: cartId,
// items: updatedItems,
// })
// console.log(updatedCart)
return currentCart
// if (updatedCart) {
// return {}
// // return updatedCart
// }
}