52 lines
1.2 KiB
TypeScript
52 lines
1.2 KiB
TypeScript
|
|
import { onMounted, onUnmounted, ref } from 'vue';
|
||
|
|
|
||
|
|
import { apiClient } from '../api/client';
|
||
|
|
import { relayDtoToDomain } from '../types/mappers/relayDtoMapper';
|
||
|
|
import type { Relay } from '../types/relay';
|
||
|
|
import { isNil } from '../utils/isNil';
|
||
|
|
|
||
|
|
export function useRelayPolling(intervalMs: number = 2000) {
|
||
|
|
const relays = ref<Relay[]>([]);
|
||
|
|
const isLoading = ref(false);
|
||
|
|
const error = ref<string | null>(null);
|
||
|
|
|
||
|
|
let pollingInterval: number | null = null;
|
||
|
|
|
||
|
|
const fetchData = async () => {
|
||
|
|
isLoading.value = true;
|
||
|
|
try {
|
||
|
|
const { data } = await apiClient.GET('/api/relays');
|
||
|
|
relays.value = data?.map(relayDtoToDomain) ?? [];
|
||
|
|
error.value = null;
|
||
|
|
} catch (err: any) {
|
||
|
|
console.error('Polling error:', err);
|
||
|
|
error.value = err.message || 'Failed to fetch data';
|
||
|
|
} finally {
|
||
|
|
isLoading.value = false;
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
const startPolling = () => {
|
||
|
|
fetchData();
|
||
|
|
pollingInterval = window.setInterval(fetchData, intervalMs);
|
||
|
|
};
|
||
|
|
|
||
|
|
const stopPolling = () => {
|
||
|
|
if (isNil(pollingInterval)) {
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
clearInterval(pollingInterval);
|
||
|
|
pollingInterval = null;
|
||
|
|
};
|
||
|
|
|
||
|
|
onMounted(startPolling);
|
||
|
|
onUnmounted(stopPolling);
|
||
|
|
|
||
|
|
return {
|
||
|
|
relays,
|
||
|
|
isLoading,
|
||
|
|
error,
|
||
|
|
refresh: fetchData,
|
||
|
|
};
|
||
|
|
}
|