73 lines
1.7 KiB
TypeScript
73 lines
1.7 KiB
TypeScript
import { computed, shallowRef } from 'vue'
|
|
import type {
|
|
HistoryResponse,
|
|
MetaResponse,
|
|
OverviewResponse,
|
|
PushRecord
|
|
} from '../types/api'
|
|
|
|
const API_BASE = 'http://127.0.0.1:10000/api'
|
|
|
|
interface DashboardState {
|
|
loading: boolean
|
|
error: string | null
|
|
meta: MetaResponse | null
|
|
overview: OverviewResponse | null
|
|
history: HistoryResponse | null
|
|
pushRecords: PushRecord[]
|
|
}
|
|
|
|
async function fetchJson<T>(path: string): Promise<T> {
|
|
const response = await fetch(`${API_BASE}${path}`)
|
|
if (!response.ok) {
|
|
throw new Error(`请求失败: ${response.status}`)
|
|
}
|
|
return response.json() as Promise<T>
|
|
}
|
|
|
|
export function useDashboardData() {
|
|
const state = shallowRef<DashboardState>({
|
|
loading: true,
|
|
error: null,
|
|
meta: null,
|
|
overview: null,
|
|
history: null,
|
|
pushRecords: []
|
|
})
|
|
|
|
async function load() {
|
|
state.value = { ...state.value, loading: true, error: null }
|
|
try {
|
|
const [meta, overview, history, pushRecordsResponse] = await Promise.all([
|
|
fetchJson<MetaResponse>('/meta'),
|
|
fetchJson<OverviewResponse>('/overview'),
|
|
fetchJson<HistoryResponse>('/history'),
|
|
fetchJson<{ records: PushRecord[] }>('/push-records')
|
|
])
|
|
|
|
state.value = {
|
|
loading: false,
|
|
error: null,
|
|
meta,
|
|
overview,
|
|
history,
|
|
pushRecords: pushRecordsResponse.records
|
|
}
|
|
} catch (error) {
|
|
state.value = {
|
|
...state.value,
|
|
loading: false,
|
|
error: error instanceof Error ? error.message : '未知错误'
|
|
}
|
|
}
|
|
}
|
|
|
|
const hasData = computed(() => Boolean(state.value.meta && state.value.overview))
|
|
|
|
return {
|
|
state,
|
|
hasData,
|
|
load
|
|
}
|
|
}
|