fix: store customer-product
This commit is contained in:
86
bo/src/stores/customer/customer-product.ts
Normal file
86
bo/src/stores/customer/customer-product.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import { useFetchJson } from '@/composable/useFetchJson'
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
|
||||
|
||||
export interface Product {
|
||||
id: number
|
||||
image: string
|
||||
name: string
|
||||
productDetails?: string
|
||||
product_id: number
|
||||
is_favorite?: boolean
|
||||
}
|
||||
|
||||
export interface ProductResponse {
|
||||
items: Product[]
|
||||
items_count: number
|
||||
}
|
||||
|
||||
export interface ApiResponse {
|
||||
message: string
|
||||
items: Product[]
|
||||
count: number
|
||||
}
|
||||
|
||||
export const useCustomerProductStore = defineStore('customer-product', () => {
|
||||
const loading = ref(true)
|
||||
const error = ref<string | null>(null)
|
||||
const route = useRoute()
|
||||
const productsList = ref<Product[]>([])
|
||||
const total = ref(0)
|
||||
const perPage = ref(15)
|
||||
|
||||
async function fetchProductList() {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
|
||||
const params = new URLSearchParams()
|
||||
|
||||
Object.entries(route.query).forEach(([key, value]) => {
|
||||
if (value) params.append(key, String(value))
|
||||
})
|
||||
|
||||
const url = `/api/v1/restricted/product/list?${params}`
|
||||
|
||||
|
||||
try {
|
||||
const response = await useFetchJson<ApiResponse>(url)
|
||||
productsList.value = response.items || []
|
||||
total.value = response.count || 0
|
||||
} catch (e: unknown) {
|
||||
error.value = e instanceof Error ? e.message : 'Failed to load products'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleFavorite(product: Product) {
|
||||
const productId = product.product_id
|
||||
const isFavorite = product.is_favorite
|
||||
|
||||
const url = `/api/v1/restricted/product/favorite/${productId}`
|
||||
|
||||
try {
|
||||
if (!isFavorite) {
|
||||
await useFetchJson(url, { method: 'POST' })
|
||||
} else {
|
||||
await useFetchJson(url, { method: 'DELETE' })
|
||||
}
|
||||
product.is_favorite = !isFavorite
|
||||
} catch (e: unknown) {
|
||||
error.value = e instanceof Error ? e.message : 'Failed to update favorite'
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
fetchProductList,
|
||||
toggleFavorite,
|
||||
productsList,
|
||||
total,
|
||||
loading,
|
||||
error,
|
||||
perPage
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user