Health Analytics API Integration
Backend Health Analytics microservice is ready for integration with the admin dashboard.
Health Analytics API Integration
Backend Health Analytics microservice is ready for integration with the admin dashboard.
API Overview
Base URL: https://api.crop.com/api/health
The Health Analytics API provides real-time system health monitoring with vendor-level data quality metrics and digital maturation pipeline tracking.
Endpoints
1. Get System Overview
GET /api/health/overviewReturns high-level system health summary with total counts and service status.
Response:
{
overall: {
status: "healthy" | "degraded" | "critical";
score: number; // 0-100
message: string;
};
totals: {
totalParts: number;
catalogReadyParts: number;
searchableParts: number;
vendorCount: number;
};
services: {
mongodb: { ok: boolean; latency?: number };
elasticsearch: { ok: boolean; latency?: number };
searchService: { ok: boolean; latency?: number };
};
lastUpdated: string; // ISO 8601
}2. List All Vendors
GET /api/health/vendorsReturns health metrics for all vendors/manufacturers.
Response:
{
vendors: VendorHealth[];
lastUpdated: string;
}3. Get Single Vendor
GET /api/health/vendors/:vendorCodeReturns detailed health metrics for a specific vendor.
Path Parameters:
vendorCode- Vendor code (e.g., "bosch", "continental")
Response:
VendorHealth // See TypeScript types below4. Get MongoDB Collections Stats
GET /api/health/collectionsReturns statistics for all MongoDB collections (both admin and manufacturer collections).
Response:
{
adminCollections: CollectionStats[];
manufacturerCollections: CollectionStats[];
lastUpdated: string;
}
interface CollectionStats {
name: string;
count: number;
size: number;
avgObjSize: number;
storageSize: number;
indexes: number;
}TypeScript Types
All TypeScript types are available in the existing lib/types/health.ts file:
import type {
VendorHealth,
SystemHealth,
CollectionStats,
QualityScore,
StageDefinition
} from "@/lib/types/health";Key Types
VendorHealth:
vendorCode,vendorName- Vendor identificationstages- 8-stage digital maturation pipeline countsquality- Quality distribution (excellent/good/fair/poor)pricing,media,fitment- Coverage metricshealthScore- Overall vendor health (0-100)integrity- Data integrity flags
SystemHealth:
overall- System-wide status and scorevendors- Array of all vendor health metricstotals- Aggregate countsservices- Dependency health checks
Authentication
All API requests must include a valid Clerk JWT token with the "api" template.
Setup
-
Configure Clerk JWT template in Dashboard:
- Template name:
api - Claims: Default claims are sufficient
- Template name:
-
Get token in your component:
import { useAuth } from "@clerk/nextjs";
const { getToken } = useAuth();
const token = await getToken({ template: "api" });- Include token in API requests:
const response = await fetch("https://api.crop.com/api/health/overview", {
headers: {
"Authorization": `Bearer ${token}`,
"Content-Type": "application/json"
}
});Integration Example
Create API Client
Create lib/health-analytics-api.ts:
import type { SystemHealth, VendorHealth, CollectionStats } from "@/lib/types/health";
const BASE_URL = process.env.NEXT_PUBLIC_HEALTH_API_URL || "https://api.crop.com/api/health";
export class HealthAnalyticsAPI {
constructor(private getToken: () => Promise<string | null>) {}
private async request<T>(endpoint: string): Promise<T> {
const token = await this.getToken();
if (!token) throw new Error("No authentication token available");
const response = await fetch(`${BASE_URL}${endpoint}`, {
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json"
},
cache: "no-store"
});
if (!response.ok) {
throw new Error(`API request failed: ${response.statusText}`);
}
return response.json();
}
async getOverview() {
return this.request<SystemHealth>("/overview");
}
async getVendors() {
return this.request<{ vendors: VendorHealth[]; lastUpdated: string }>("/vendors");
}
async getVendor(vendorCode: string) {
return this.request<VendorHealth>(`/vendors/${vendorCode}`);
}
async getCollections() {
return this.request<{
adminCollections: CollectionStats[];
manufacturerCollections: CollectionStats[];
lastUpdated: string;
}>("/collections");
}
}Use in Component
"use client";
import { useAuth } from "@clerk/nextjs";
import { useEffect, useState } from "react";
import { HealthAnalyticsAPI } from "@/lib/health-analytics-api";
import type { SystemHealth } from "@/lib/types/health";
export function HealthDashboard() {
const { getToken } = useAuth();
const [health, setHealth] = useState<SystemHealth | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const api = new HealthAnalyticsAPI(() => getToken({ template: "api" }));
api.getOverview()
.then(setHealth)
.catch(console.error)
.finally(() => setLoading(false));
}, [getToken]);
if (loading) return <div>Loading...</div>;
if (!health) return <div>Failed to load health data</div>;
return (
<div>
<h1>System Health: {health.overall.status}</h1>
<p>Score: {health.overall.score}/100</p>
{/* Render health metrics */}
</div>
);
}Environment Variables
Add to .env.local:
# Health Analytics API
NEXT_PUBLIC_HEALTH_API_URL=https://api.crop.com/api/health
# Clerk (if not already configured)
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_...
CLERK_SECRET_KEY=sk_...
NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-upData Refresh Strategy
The Health Analytics API provides near-real-time data. Recommended refresh strategies:
- Overview Dashboard: Refresh every 30 seconds
- Vendor Details: Refresh every 60 seconds
- Collections Stats: Refresh every 5 minutes (less volatile)
Example with auto-refresh:
useEffect(() => {
const api = new HealthAnalyticsAPI(() => getToken({ template: "api" }));
const fetchData = () => {
api.getOverview().then(setHealth).catch(console.error);
};
fetchData(); // Initial fetch
const interval = setInterval(fetchData, 30000); // Every 30s
return () => clearInterval(interval);
}, [getToken]);Error Handling
The API returns standard HTTP status codes:
200- Success401- Unauthorized (invalid/missing token)404- Resource not found (e.g., invalid vendor code)500- Internal server error
Always implement proper error handling:
try {
const data = await api.getOverview();
setHealth(data);
} catch (error) {
if (error instanceof Error) {
if (error.message.includes("401")) {
// Token expired or invalid - trigger re-authentication
await signOut();
} else {
// Show user-friendly error message
setError("Failed to load health data. Please try again.");
}
}
}Migration from Mock Data
Current Source Tab uses mock data. To migrate:
- Create
HealthAnalyticsAPIclient (see above) - Replace mock data in
app/(dashboard)/dashboard/health/_components/source-tab.tsx - Add loading and error states
- Implement auto-refresh
- Remove mock data and alerts about backend requirements
Next Steps
-
Clerk Configuration
- Set up JWT template in Clerk Dashboard
- Configure domains (admin.crop.com)
- Test token generation
-
API Integration
- Create Health Analytics API client
- Update Source Tab component
- Add loading states and error handling
- Implement auto-refresh
-
Testing
- Test authentication flow
- Verify API responses match TypeScript types
- Test error scenarios (network failure, auth errors)
- Performance testing with auto-refresh
-
Production Deployment
- Update environment variables
- Configure CORS if needed
- Monitor API performance
- Set up error tracking (Sentry, etc.)
Support
- Backend API documentation:
services/health-analytics/README.md - TypeScript types:
lib/types/health.ts - Clerk integration:
docs/CLERK_FRONTEND_INTEGRATION.md
For questions or issues, contact the backend team.