Files
your-gold/stores/productStore.ts
2025-06-24 15:53:07 +02:00

115 lines
2.8 KiB
TypeScript

import { NuxtErrorBoundary } from "#components";
import { useMyFetch } from "#imports";
import type {
GenericResponse,
GenericResponseChildren,
GenericResponseItems,
UserCart,
} from "~/types";
import type { Product } from "~/types/product";
export const useProductStore = defineStore("productStore", () => {
const productList = ref<Product[]>();
const modules = ref();
async function getList(count: number, categoryId = 1) {
try {
const { data } = await useMyFetch<GenericResponseItems<[]>>(
`/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<GenericResponseChildren<[]>>(
`/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 addToCart(product: Product) {
try {
const { data } = await useMyFetch<GenericResponse<UserCart>>(
`/api/public/user/cart/item/add/${product.id}/1`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
},
onErrorOccured: (_, status) => {
throw new Error(`HTTP error: ${status}`);
},
}
);
} catch (error) {
console.error("getList error:", error);
}
}
const cart = ref({} as UserCart);
async function getCart() {
try {
const { data } = await useMyFetch<GenericResponse<UserCart>>(
`/api/public/user/cart`,
{
headers: {
"Content-Type": "application/json",
},
onErrorOccured: (_, status) => {
throw new Error(`HTTP error: ${status}`);
},
}
);
// if (!res.ok) {
// throw new Error(`HTTP error: ${res.status}`);
// }
cart.value = data;
} catch (error) {
console.error("getList error:", error);
}
}
return {
productList,
modules,
getList,
getModules,
addToCart,
// getCart,
};
});