Files
your-gold/stores/productStore.ts

106 lines
2.3 KiB
TypeScript

export const useProductStore = defineStore("productStore", () => {
const productList = ref();
const modules = ref();
async function getList(count: number, categoryId = 1) {
try {
const res = await fetch(
`http://127.0.0.1:4000/api/public/products/category/${categoryId}?p=1&elems=${count}`,
{
headers: {
"Content-Type": "application/json",
},
}
);
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();
async function getCart() {
try {
const res = await fetch(`http://127.0.0.1:4000/api/public/user/cart`, {
headers: {
"Content-Type": "application/json",
},
});
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,
};
});