import { useMyFetch } from "#imports"; import type { CartItem, GenericResponse, GenericResponseChildren, GenericResponseItems, UserCart, } from "~/types"; import type { Product } from "~/types/product"; export const useProductStore = defineStore("productStore", () => { const productList = ref(); const modules = ref(); async function getList(count: number, categoryId = 1) { try { const { data } = await useMyFetch>( `/api/public/products/category/${categoryId}?p=1&elems=${count}`, { headers: { "Content-Type": "application/json", }, onErrorOccured: async (_, status) => { // await navigateTo("/error", { replace: true }); throw createError({ statusCode: status, statusMessage: `HTTP error: ${status}`, }); }, } ); productList.value = data.items; } catch (error) { console.error("getList error:", error); } } async function getModules() { try { const { data } = await useMyFetch>( `/api/public/module/e_shop`, { headers: { "Content-Type": "application/json", }, onErrorOccured: (_, status) => { throw new Error(`HTTP error: ${status}`); }, } ); modules.value = data.children.find( (item: { id: number; name: string }) => item.name === "currency_rates_bar" ); } catch (error) { console.error("getList error:", error); } } async function incrementCartItem(id: number) { try { await useMyFetch( `/api/public/user/cart/item/add/${id}/1`, { method: "PUT", headers: { "Content-Type": "application/json", }, onErrorOccured: (_, status) => { throw new Error(`HTTP error: ${status}`); }, } ); getCart(); } catch (error) { console.error("getList error:", error); } } async function decrementCartItem(id: number) { try { await useMyFetch( `/api/public/user/cart/item/subtract/${id}/1`, { method: "PUT", headers: { "Content-Type": "application/json", }, onErrorOccured: (_, status) => { throw new Error(`HTTP error: ${status}`); }, } ); getCart(); } catch (error) { console.error("removeFromCart error:", error); } } async function deleteCartItem(id: number) { try { await useMyFetch( `/api/public/user/cart/item/${id}`, { method: "DELETE", headers: { "Content-Type": "application/json", }, onErrorOccured: (_, status) => { throw new Error(`HTTP error: ${status}`); }, } ); getCart(); } catch (error) { console.error("removeFromCart error:", error); } } const cart = ref({} as UserCart); async function getCart() { try { const { data } = await useMyFetch>( `/api/public/user/cart`, { headers: { "Content-Type": "application/json", }, onErrorOccured: (_, status) => { throw new Error(`HTTP error: ${status}`); }, } ); cart.value = data; } catch (error) { console.error("getList error:", error); } } return { productList, modules, cart, getList, getModules, incrementCartItem, decrementCartItem, deleteCartItem, getCart, }; });