useStatus.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { onBeforeUnmount, onMounted, ref, shallowRef } from 'vue';
  2. import { HttpUtil } from '@/utils';
  3. import { Status } from '@/models/status.js';
  4. const POLL_INTERVAL_MS = 2000;
  5. // Polls /panel/api/server/status and exposes a reactive Status object
  6. // + a `fetched` flag so consumers can show a spinner before the first
  7. // successful fetch.
  8. //
  9. // WebSocket integration is intentionally deferred to a later sub-phase.
  10. // Polling at 2s is the same fallback the legacy panel falls back to
  11. // when its websocket link drops, so we're shipping the proven path
  12. // first and adding the websocket on top later.
  13. export function useStatus() {
  14. const status = shallowRef(new Status());
  15. const fetched = ref(false);
  16. let timer = null;
  17. async function refresh() {
  18. try {
  19. const msg = await HttpUtil.get('/panel/api/server/status');
  20. if (msg?.success) {
  21. status.value = new Status(msg.obj);
  22. if (!fetched.value) fetched.value = true;
  23. }
  24. } catch (e) {
  25. console.error('Failed to get status:', e);
  26. }
  27. }
  28. onMounted(() => {
  29. refresh();
  30. timer = window.setInterval(refresh, POLL_INTERVAL_MS);
  31. });
  32. onBeforeUnmount(() => {
  33. if (timer != null) window.clearInterval(timer);
  34. });
  35. return { status, fetched, refresh };
  36. }