59 lines
1.9 KiB
TypeScript
59 lines
1.9 KiB
TypeScript
import { useFetchJson } from '@/composable/useFetchJson'
|
|
import { defineStore } from 'pinia'
|
|
import { ref } from 'vue'
|
|
|
|
export interface Address {
|
|
id: number
|
|
country_id: number
|
|
address_unparsed: Record<string, string>
|
|
}
|
|
|
|
export const useAddressStore = defineStore('address', () => {
|
|
const addresses = ref<Address[]>([])
|
|
const loading = ref(false)
|
|
const error = ref<string | null>(null)
|
|
|
|
async function fetchAddresses() {
|
|
loading.value = true
|
|
error.value = null
|
|
try {
|
|
const res = await useFetchJson<Address[]>('/api/v1/restricted/addresses/retrieve-addresses')
|
|
addresses.value = res.items ?? []
|
|
} catch (e: unknown) {
|
|
error.value = e instanceof Error ? e.message : 'Failed to load addresses'
|
|
} finally {
|
|
loading.value = false
|
|
}
|
|
}
|
|
|
|
async function deleteAddress(id: number) {
|
|
await useFetchJson(`/api/v1/restricted/addresses/delete-address?address_id=${id}`, { method: 'DELETE' })
|
|
addresses.value = addresses.value.filter((a) => a.id !== id)
|
|
}
|
|
|
|
async function getTemplate(countryId: number): Promise<Record<string, string>> {
|
|
const res = await useFetchJson<Record<string, string>>(
|
|
`/api/v1/restricted/addresses/get-template?country_id=${countryId}`
|
|
)
|
|
return res.items ?? {}
|
|
}
|
|
|
|
async function createAddress(countryId: number, data: Record<string, string>) {
|
|
await useFetchJson(`/api/v1/restricted/addresses/add-new-address?country_id=${countryId}`, {
|
|
method: 'POST',
|
|
body: JSON.stringify(data)
|
|
})
|
|
await fetchAddresses()
|
|
}
|
|
|
|
async function updateAddress(id: number, countryId: number, data: Record<string, string>) {
|
|
await useFetchJson(`/api/v1/restricted/addresses/modify-address?country_id=${countryId}&address_id=${id}`, {
|
|
method: 'POST',
|
|
body: JSON.stringify(data)
|
|
})
|
|
await fetchAddresses()
|
|
}
|
|
|
|
return { addresses, loading, error, fetchAddresses, deleteAddress, getTemplate, createAddress, updateAddress }
|
|
})
|