feat: add relay composables
This commit is contained in:
51
src/composables/useRelayPolling.ts
Normal file
51
src/composables/useRelayPolling.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user