Files
your-gold/stores/productStore.ts
2025-06-24 12:05:43 +02:00

113 lines
2.7 KiB
TypeScript

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