diff options
Diffstat (limited to 'storefront/lib/storefront.js')
| -rw-r--r-- | storefront/lib/storefront.js | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/storefront/lib/storefront.js b/storefront/lib/storefront.js new file mode 100644 index 0000000..b6433a9 --- /dev/null +++ b/storefront/lib/storefront.js @@ -0,0 +1,66 @@ +export const cartStorageKey = "lsb_cart_id" +export const tokenStorageKey = "lsb_customer_token" + +export const getStoredCartId = () => { + if (typeof window === "undefined") { + return null + } + return window.localStorage.getItem(cartStorageKey) +} + +export const setStoredCartId = (cartId) => { + if (typeof window === "undefined") { + return + } + window.localStorage.setItem(cartStorageKey, cartId) +} + +export const clearStoredCartId = () => { + if (typeof window === "undefined") { + return + } + window.localStorage.removeItem(cartStorageKey) +} + +export const getStoredToken = () => { + if (typeof window === "undefined") { + return null + } + return window.localStorage.getItem(tokenStorageKey) +} + +export const setStoredToken = (token) => { + if (typeof window === "undefined") { + return + } + window.localStorage.setItem(tokenStorageKey, token) +} + +export const clearStoredToken = () => { + if (typeof window === "undefined") { + return + } + window.localStorage.removeItem(tokenStorageKey) +} + +export const ensureCart = async (client) => { + const storedCartId = getStoredCartId() + + if (storedCartId) { + try { + const { cart } = await client.carts.retrieve(storedCartId) + return cart + } catch (error) { + clearStoredCartId() + } + } + + const { regions } = await client.regions.list() + if (!regions?.length) { + throw new Error("Aucune région disponible pour créer un panier.") + } + + const { cart } = await client.carts.create({ region_id: regions[0].id }) + setStoredCartId(cart.id) + return cart +} |
