From 51411981678ac0005d5ea9d4da8699dcdb695c07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fe=CC=81lix=20Pe=CC=81ault?= Date: Mon, 8 Nov 2021 12:14:39 +0100 Subject: [PATCH] Move functions to directory --- src/routes/api/swell.ts | 9 ++++- .../{functions.ts => functions/index.ts} | 0 src/utils/{ => functions}/notifications.ts | 0 src/utils/functions/shop.ts | 33 +++++++++++++++++++ .../{swellFunctions.ts => functions/swell.ts} | 0 src/utils/{store.ts => stores/index.ts} | 0 6 files changed, 41 insertions(+), 1 deletion(-) rename src/utils/{functions.ts => functions/index.ts} (100%) rename src/utils/{ => functions}/notifications.ts (100%) create mode 100644 src/utils/functions/shop.ts rename src/utils/{swellFunctions.ts => functions/swell.ts} (100%) rename src/utils/{store.ts => stores/index.ts} (100%) diff --git a/src/routes/api/swell.ts b/src/routes/api/swell.ts index 61992f1..7c55e55 100644 --- a/src/routes/api/swell.ts +++ b/src/routes/api/swell.ts @@ -1,4 +1,11 @@ -import { addToCart, createCart, fetchCart, getProduct, removeCartItem, updateCartItem } from '$utils/swellFunctions' +import { + addToCart, + createCart, + fetchCart, + getProduct, + removeCartItem, + updateCartItem +} from '$utils/functions/swell' // Block GET requests diff --git a/src/utils/functions.ts b/src/utils/functions/index.ts similarity index 100% rename from src/utils/functions.ts rename to src/utils/functions/index.ts diff --git a/src/utils/notifications.ts b/src/utils/functions/notifications.ts similarity index 100% rename from src/utils/notifications.ts rename to src/utils/functions/notifications.ts diff --git a/src/utils/functions/shop.ts b/src/utils/functions/shop.ts new file mode 100644 index 0000000..29bfe70 --- /dev/null +++ b/src/utils/functions/shop.ts @@ -0,0 +1,33 @@ +import { addNotification } from '$utils/functions/notifications' +import type { Writable } from 'svelte/store' + + +/** + * Add a product to a cart + */ +export const addToCart = async (cart: string, cartData: Writable, product: any, quantity: number = 1) => { + if (cart && cart !== 'null') { + const updatedCart = await fetch('/api/swell', { + method: 'POST', + body: JSON.stringify({ + action: 'addToCart', + cartId: cart, + productId: product.id, + quantity, + }) + }) + if (updatedCart.ok) { + const newCart = await updatedCart.json() + cartData.set(newCart) + + // Show notification + addNotification({ + title: 'Added to cart', + name: `${product.name} - x1`, + image: product.images[0].file.url, + }) + } + } else { + console.log('No active cart') + } +} \ No newline at end of file diff --git a/src/utils/swellFunctions.ts b/src/utils/functions/swell.ts similarity index 100% rename from src/utils/swellFunctions.ts rename to src/utils/functions/swell.ts diff --git a/src/utils/store.ts b/src/utils/stores/index.ts similarity index 100% rename from src/utils/store.ts rename to src/utils/stores/index.ts