useMetrics.js

import { useState, useEffect } from 'react';
import axios from 'axios';

const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:8080';
const REFRESH_INTERVAL = parseInt(import.meta.env.VITE_REFRESH_INTERVAL || '30000');

export function useMetrics() {
  const [summary, setSummary] = useState(null);
  const [topPaths, setTopPaths] = useState([]);
  const [diagnostics, setDiagnostics] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchMetrics = async () => {
    try {
      const [summaryRes, pathsRes, diagRes] = await Promise.all([
        axios.get(`${API_URL}/api/summary`),
        axios.get(`${API_URL}/api/paths/top`),
        axios.get(`${API_URL}/api/diagnostics`),
      ]);

      setSummary(summaryRes.data);
      setTopPaths(pathsRes.data);
      setDiagnostics(diagRes.data);
      setError(null);
    } catch (err) {
      console.error('Error fetching metrics:', err);
      setError(err.message || 'Failed to load metrics');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMetrics();
    const interval = setInterval(fetchMetrics, REFRESH_INTERVAL);
    return () => clearInterval(interval);
  }, []);

  return { summary, topPaths, diagnostics, loading, error };
}

export function usePathDetail(pathId) {
  const [detail, setDetail] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!pathId) return;

    const fetchDetail = async () => {
      try {
        setLoading(true);
        const res = await axios.get(`${API_URL}/api/path/${pathId}`);
        setDetail(res.data);
        setError(null);
      } catch (err) {
        console.error('Error fetching path detail:', err);
        setError(err.message || 'Failed to load path detail');
      } finally {
        setLoading(false);
      }
    };

    fetchDetail();
  }, [pathId]);

  return { detail, loading, error };
}

export function useEdgeHistory(edgeId, days = 7) {
  const [history, setHistory] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!edgeId) return;

    const fetchHistory = async () => {
      try {
        const res = await axios.get(`${API_URL}/api/edge/${edgeId}/history?days=${days}`);
        setHistory(res.data.history || []);
      } catch (err) {
        console.error('Error fetching edge history:', err);
        setHistory([]);
      } finally {
        setLoading(false);
      }
    };

    fetchHistory();
  }, [edgeId, days]);

  return { history, loading };
}
← All docsView source on GitHub →