Skip to content

Commit

Permalink
WIP still refreshing on fetch
Browse files Browse the repository at this point in the history
  • Loading branch information
mfreeman451 committed Feb 26, 2025
1 parent 7f49d97 commit a745e73
Showing 1 changed file with 63 additions and 57 deletions.
120 changes: 63 additions & 57 deletions serviceradar-next/src/app/service/[nodeid]/[servicename]/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,105 +2,111 @@
import { Suspense } from 'react';
import ServiceDashboard from '../../../../components/ServiceDashboard';

export const revalidate = 30; // Increase revalidation time from 10 to 30 seconds
export const revalidate = 30;

// Async function to fetch data on the server with API key authentication
async function fetchServiceData(nodeId, serviceName) {
try {
// When running on the server, use the full backend URL
const backendUrl = process.env.NEXT_PUBLIC_BACKEND_URL;
const apiKey = process.env.API_KEY;
const backendUrl = process.env.NEXT_PUBLIC_BACKEND_URL || 'http://localhost:8090';
const apiKey = process.env.API_KEY || '';

// Fetch nodes list
const nodesResponse = await fetch(`${backendUrl}/api/nodes`, {
headers: {
'X-API-Key': apiKey
},
next: { revalidate: 30 } // Cache for 30 seconds
headers: { 'X-API-Key': apiKey },
next: { revalidate: 30 },
});

if (!nodesResponse.ok) {
throw new Error(`Nodes API request failed: ${nodesResponse.status}`);
}
const nodes = await nodesResponse.json();

// Find the specific node
const node = nodes.find((n) => n.node_id === nodeId);
if (!node) {
return { error: 'Node not found' };
}
if (!node) return { error: 'Node not found' };

// Find the specific service
const service = node.services?.find((s) => s.name === serviceName);
if (!service) {
return { error: 'Service not found' };
}
if (!service) return { error: 'Service not found' };

// Fetch metrics data
let metrics = [];
try {
const metricsResponse = await fetch(`${backendUrl}/api/nodes/${nodeId}/metrics`, {
headers: {
'X-API-Key': apiKey
},
next: { revalidate: 30 } // Cache for 30 seconds
headers: { 'X-API-Key': apiKey },
next: { revalidate: 30 },
});

if (!metricsResponse.ok) {
throw new Error(`Metrics API request failed: ${metricsResponse.status}`);
console.error(`Metrics API failed: ${metricsResponse.status} - ${await metricsResponse.text()}`);
} else {
metrics = await metricsResponse.json();
}

const metrics = await metricsResponse.json();
const serviceMetrics = metrics.filter(
(m) => m.service_name === serviceName
);

return { service, metrics: serviceMetrics };
} catch (metricsError) {
console.error('Error fetching metrics data:', metricsError);
// Don't fail the whole request if metrics fail
return { service, metrics: [] };
}
const serviceMetrics = metrics.filter((m) => m.service_name === serviceName);

let snmpData = [];
if (service.type === 'snmp') {
try {
const end = new Date();
const start = new Date();
start.setHours(end.getHours() - 1);

const snmpUrl = `${backendUrl}/api/nodes/${nodeId}/snmp?start=${start.toISOString()}&end=${end.toISOString()}`;
console.log("Fetching SNMP from:", snmpUrl);

const snmpResponse = await fetch(snmpUrl, {
headers: { 'X-API-Key': apiKey },
next: { revalidate: 30 },
});

if (!snmpResponse.ok) {
const errorText = await snmpResponse.text();
console.error(`SNMP API failed: ${snmpResponse.status} - ${errorText}`);
throw new Error(`SNMP API request failed: ${snmpResponse.status} - ${errorText}`);
}
snmpData = await snmpResponse.json();
console.log("SNMP data fetched:", snmpData.length);
} catch (snmpError) {
console.error('Error fetching SNMP data:', snmpError);
}
}

return { service, metrics: serviceMetrics, snmpData };
} catch (err) {
console.error('Error fetching data:', err);
return { error: err.message };
}
}

// Generate dynamic metadata for the page
export async function generateMetadata(props) {
// Next.js now requires us to await the params object
const params = await props.params;

// Now we can safely destructure
const nodeid = params.nodeid;
const servicename = params.servicename;

export async function generateMetadata({ params }) {
const { nodeid, servicename } = await params;
return {
title: `${servicename} on ${nodeid} - ServiceRadar`,
};
}

export default async function Page(props) {
// Access params using the props object
const params = props.params;

// Now use the params after they're fully resolved
const nodeid = params.nodeid;
const servicename = params.servicename;

// Fetch data
export default async function Page({ params }) {
const { nodeid, servicename } = await params;
const initialData = await fetchServiceData(nodeid, servicename);

console.log("Page fetched data:", {
service: !!initialData.service,
metricsLength: initialData.metrics?.length,
snmpDataLength: initialData.snmpData?.length,
error: initialData.error,
});

return (
<div>
<Suspense fallback={<div className="flex justify-center items-center h-64">
<div className="text-lg text-gray-600 dark:text-gray-300">Loading service data...</div>
</div>}>
<Suspense
fallback={
<div className="flex justify-center items-center h-64">
<div className="text-lg text-gray-600 dark:text-gray-300">Loading service data...</div>
</div>
}
>
<ServiceDashboard
nodeId={nodeid}
serviceName={servicename}
initialService={initialData.service}
initialMetrics={initialData.metrics}
initialMetrics={initialData.metrics || []}
initialSnmpData={initialData.snmpData || []}
initialError={initialData.error}
/>
</Suspense>
Expand Down

0 comments on commit a745e73

Please sign in to comment.