Files
tp/main_dc/yalarba/yalarba-nuxt/app/stores/objects.ts
T

112 lines
3.2 KiB
TypeScript

import { defineStore } from 'pinia'
import type { TourObject, TourObjectFilters, PaginatedResponse } from '~/types'
interface ObjectsState {
objects: TourObject[]
currentObject: TourObject | null
total: number
page: number
totalPages: number
loading: boolean
error: string | null
}
export const useObjectsStore = defineStore('objects', {
state: (): ObjectsState => ({
objects: [],
currentObject: null,
total: 0,
page: 1,
totalPages: 0,
loading: false,
error: null,
}),
actions: {
async fetchObjects(filters?: TourObjectFilters) {
this.loading = true
this.error = null
try {
const api = useApi()
const params = new URLSearchParams()
if (filters?.category_id) params.set('category_id', String(filters.category_id))
if (filters?.city) params.set('city', filters.city)
if (filters?.rating_min) params.set('rating_min', String(filters.rating_min))
if (filters?.sort_by) params.set('sort_by', filters.sort_by)
if (filters?.sort_order) params.set('sort_order', filters.sort_order)
if (filters?.page) params.set('page', String(filters.page))
if (filters?.per_page) params.set('per_page', String(filters.per_page))
const query = params.toString()
const response = await api.get<PaginatedResponse<TourObject>>(`/objects${query ? `?${query}` : ''}`)
this.objects = response.items ?? []
this.total = response.total
this.page = response.page
this.totalPages = response.total_pages
} catch (e: any) {
this.error = e.message || 'Failed to fetch objects'
} finally {
this.loading = false
}
},
async fetchObject(id: number) {
this.loading = true
this.error = null
try {
const api = useApi()
this.currentObject = await api.get<TourObject>(`/objects/${id}`)
} catch (e: any) {
this.error = e.message || 'Failed to fetch object'
} finally {
this.loading = false
}
},
async createObject(data: Partial<TourObject>) {
this.loading = true
this.error = null
try {
const api = useApi()
const response = await api.post<TourObject>('/objects', data)
return response
} catch (e: any) {
this.error = e.message || 'Failed to create object'
throw e
} finally {
this.loading = false
}
},
async updateObject(id: number, data: Partial<TourObject>) {
this.loading = true
this.error = null
try {
const api = useApi()
const response = await api.put<TourObject>(`/objects/${id}`, data)
return response
} catch (e: any) {
this.error = e.message || 'Failed to update object'
throw e
} finally {
this.loading = false
}
},
async deleteObject(id: number) {
this.loading = true
this.error = null
try {
const api = useApi()
await api.delete(`/objects/${id}`)
this.objects = this.objects.filter((o) => o.id !== id)
} catch (e: any) {
this.error = e.message || 'Failed to delete object'
throw e
} finally {
this.loading = false
}
},
},
})