49 lines
1.4 KiB
TypeScript
49 lines
1.4 KiB
TypeScript
|
|
import type { HistoryEntry } from '~/types'
|
||
|
|
|
||
|
|
export const useHistory = (clientId: number) => {
|
||
|
|
const entries = ref<HistoryEntry[]>([])
|
||
|
|
|
||
|
|
const getXsrfToken = (): string => {
|
||
|
|
const match = document.cookie.match(/XSRF-TOKEN=([^;]+)/)
|
||
|
|
return match ? decodeURIComponent(match[1]) : ''
|
||
|
|
}
|
||
|
|
|
||
|
|
const fetchEntries = async (): Promise<void> => {
|
||
|
|
const response = await $fetch<{ data: HistoryEntry[] }>(`/api/clients/${clientId}/history`, {
|
||
|
|
credentials: 'include',
|
||
|
|
})
|
||
|
|
entries.value = response.data
|
||
|
|
}
|
||
|
|
|
||
|
|
const addEntry = async (payload: { type: string; body: string }): Promise<void> => {
|
||
|
|
await $fetch(`/api/clients/${clientId}/history`, {
|
||
|
|
method: 'POST',
|
||
|
|
body: payload,
|
||
|
|
credentials: 'include',
|
||
|
|
headers: { 'X-XSRF-TOKEN': getXsrfToken() },
|
||
|
|
})
|
||
|
|
await fetchEntries()
|
||
|
|
}
|
||
|
|
|
||
|
|
const updateEntry = async (id: number, body: string): Promise<void> => {
|
||
|
|
await $fetch(`/api/history/${id}`, {
|
||
|
|
method: 'PUT',
|
||
|
|
body: { body },
|
||
|
|
credentials: 'include',
|
||
|
|
headers: { 'X-XSRF-TOKEN': getXsrfToken() },
|
||
|
|
})
|
||
|
|
await fetchEntries()
|
||
|
|
}
|
||
|
|
|
||
|
|
const deleteEntry = async (id: number): Promise<void> => {
|
||
|
|
await $fetch(`/api/history/${id}`, {
|
||
|
|
method: 'DELETE',
|
||
|
|
credentials: 'include',
|
||
|
|
headers: { 'X-XSRF-TOKEN': getXsrfToken() },
|
||
|
|
})
|
||
|
|
entries.value = entries.value.filter(e => e.id !== id)
|
||
|
|
}
|
||
|
|
|
||
|
|
return { entries, fetchEntries, addEntry, updateEntry, deleteEntry }
|
||
|
|
}
|