68 lines
1.7 KiB
TypeScript
68 lines
1.7 KiB
TypeScript
import { ref } from 'vue'
|
||
import { useApi } from '~/composables/useApi'
|
||
|
||
export type ComponentHistoryActor = {
|
||
id: string
|
||
label: string
|
||
}
|
||
|
||
export type ComponentHistoryEntry = {
|
||
id: string
|
||
action: 'create' | 'update' | 'delete' | string
|
||
createdAt: string
|
||
actor: ComponentHistoryActor | null
|
||
diff: Record<string, { from: unknown; to: unknown }> | null
|
||
snapshot: Record<string, unknown> | null
|
||
}
|
||
|
||
const extractItems = (payload: any): ComponentHistoryEntry[] => {
|
||
if (Array.isArray(payload?.items)) {
|
||
return payload.items
|
||
}
|
||
if (Array.isArray(payload?.member)) {
|
||
return payload.member
|
||
}
|
||
if (Array.isArray(payload?.['hydra:member'])) {
|
||
return payload['hydra:member']
|
||
}
|
||
return []
|
||
}
|
||
|
||
export function useComponentHistory () {
|
||
const { get } = useApi()
|
||
|
||
const history = ref<ComponentHistoryEntry[]>([])
|
||
const loading = ref(false)
|
||
const error = ref<string | null>(null)
|
||
|
||
const loadHistory = async (componentId: string) => {
|
||
loading.value = true
|
||
error.value = null
|
||
try {
|
||
const result = await get(`/composants/${componentId}/history`)
|
||
if (!result.success) {
|
||
error.value = result.error ?? 'Impossible de charger l’historique.'
|
||
history.value = []
|
||
return result
|
||
}
|
||
history.value = extractItems(result.data) as ComponentHistoryEntry[]
|
||
return { success: true, data: history.value }
|
||
} catch (err: any) {
|
||
const message = err?.message ?? 'Erreur inconnue'
|
||
error.value = message
|
||
history.value = []
|
||
return { success: false, error: message }
|
||
} finally {
|
||
loading.value = false
|
||
}
|
||
}
|
||
|
||
return {
|
||
history,
|
||
loading,
|
||
error,
|
||
loadHistory,
|
||
}
|
||
}
|
||
|