All files / src/app/docs/developer/api page.tsx

0% Statements 0/60
0% Branches 0/26
0% Functions 0/11
0% Lines 0/55

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222                                                                                                                                                                                                                                                                                                                                                                                                                                                           
"use client";
 
import { useEffect, useRef, useState } from "react";
import Link from "next/link";
import {
  ArrowLeft,
  ExternalLink,
  Download,
  FileJson,
  AlertCircle,
  Loader2,
} from "lucide-react";
 
const IS_STATIC = process.env.NEXT_PUBLIC_STATIC_EXPORT === "true";
const BASE_PATH = IS_STATIC ? "/MinimumViableHealthDataspacev2" : "";
const OPENAPI_URL = `${BASE_PATH}/openapi.yaml`;
const SWAGGER_CSS = `${BASE_PATH}/swagger-ui/swagger-ui.css`;
const SWAGGER_BUNDLE = `${BASE_PATH}/swagger-ui/swagger-ui-bundle.js`;
const SWAGGER_PRESET = `${BASE_PATH}/swagger-ui/swagger-ui-standalone-preset.js`;
 
declare global {
  interface Window {
    SwaggerUIBundle?: ((config: Record<string, unknown>) => unknown) & {
      presets: { apis: unknown };
      SwaggerUIStandalonePreset?: unknown;
    };
    SwaggerUIStandalonePreset?: unknown;
  }
}
 
type Status = "loading" | "ready" | "error";
 
function loadCss(href: string): void {
  if (document.querySelector(`link[href="${href}"]`)) return;
  const link = document.createElement("link");
  link.rel = "stylesheet";
  link.href = href;
  document.head.appendChild(link);
}
 
function loadScript(src: string): Promise<void> {
  return new Promise((resolve, reject) => {
    const existing = document.querySelector(
      `script[src="${src}"]`,
    ) as HTMLScriptElement | null;
    if (existing) {
      if (existing.dataset.loaded === "true") {
        resolve();
        return;
      }
      existing.addEventListener("load", () => resolve());
      existing.addEventListener("error", () =>
        reject(new Error(`Failed to load ${src}`)),
      );
      return;
    }
    const script = document.createElement("script");
    script.src = src;
    script.async = true;
    script.onload = () => {
      script.dataset.loaded = "true";
      resolve();
    };
    script.onerror = () => reject(new Error(`Failed to load ${src}`));
    document.body.appendChild(script);
  });
}
 
export default function ApiReferencePage() {
  const containerRef = useRef<HTMLDivElement>(null);
  const [status, setStatus] = useState<Status>("loading");
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
 
  useEffect(() => {
    let cancelled = false;
 
    async function init() {
      try {
        loadCss(SWAGGER_CSS);
 
        const specResponse = await fetch(OPENAPI_URL, { cache: "no-cache" });
        if (!specResponse.ok) {
          throw new Error(
            `Could not fetch ${OPENAPI_URL} (HTTP ${specResponse.status})`,
          );
        }
        await specResponse.text();
 
        await loadScript(SWAGGER_BUNDLE);
        await loadScript(SWAGGER_PRESET);
 
        if (cancelled) return;
        if (!window.SwaggerUIBundle || !containerRef.current) {
          throw new Error("Swagger UI bundle did not initialise");
        }
 
        window.SwaggerUIBundle({
          url: OPENAPI_URL,
          domNode: containerRef.current,
          deepLinking: true,
          presets: [
            window.SwaggerUIBundle.presets.apis,
            window.SwaggerUIStandalonePreset,
          ],
          layout: "BaseLayout",
          docExpansion: "list",
          filter: true,
          tryItOutEnabled: true,
          persistAuthorization: true,
        });
 
        setStatus("ready");
      } catch (err) {
        if (cancelled) return;
        const message = err instanceof Error ? err.message : String(err);
        setErrorMsg(message);
        setStatus("error");
      }
    }
 
    init();
    return () => {
      cancelled = true;
    };
  }, []);
 
  return (
    <div className="min-h-screen bg-[var(--background)] text-[var(--text-primary)]">
      <div className="max-w-7xl mx-auto px-6 py-8">
        <Link
          href="/docs/developer#api-reference"
          className="inline-flex items-center gap-2 text-sm text-[var(--text-secondary)] hover:text-[var(--text-primary)] mb-4"
        >
          <ArrowLeft className="w-4 h-4" />
          Back to Developer Guide
        </Link>
 
        <div className="mb-6">
          <h1 className="text-3xl font-bold mb-2">Interactive API Reference</h1>
          <p className="text-[var(--text-secondary)]">
            OpenAPI 3.1 specification for all 38 Next.js API routes (DSP 2025-1,
            DCP v1.0, FHIR R4, OMOP CDM, HealthDCAT-AP). Use{" "}
            <strong>Try it out</strong> to call live endpoints — most routes
            require a NextAuth session cookie.
          </p>
        </div>
 
        <div className="flex flex-wrap gap-3 mb-6 text-sm">
          <a
            href={OPENAPI_URL}
            download="mvhdv2-openapi.yaml"
            className="inline-flex items-center gap-2 px-3 py-1.5 rounded-md border border-[var(--border)] bg-[var(--surface-2)] hover:bg-[var(--surface-3)] transition-colors"
          >
            <Download className="w-4 h-4" />
            Download openapi.yaml
          </a>
          <Link
            href="/docs/developer#api-reference"
            className="inline-flex items-center gap-2 px-3 py-1.5 rounded-md border border-[var(--border)] bg-[var(--surface-2)] hover:bg-[var(--surface-3)] transition-colors"
          >
            <FileJson className="w-4 h-4" />
            Route summary table
          </Link>
          <a
            href="https://github.com/ma3u/MinimumViableHealthDataspacev2/tree/main/bruno/MVHDv2"
            target="_blank"
            rel="noopener noreferrer"
            className="inline-flex items-center gap-2 px-3 py-1.5 rounded-md border border-[var(--border)] bg-[var(--surface-2)] hover:bg-[var(--surface-3)] transition-colors"
          >
            <ExternalLink className="w-4 h-4" />
            Bruno collection
          </a>
        </div>
 
        {status === "loading" && (
          <div className="rounded-lg border border-[var(--border)] bg-[var(--surface-2)] p-10 flex flex-col items-center gap-3 text-[var(--text-secondary)]">
            <Loader2 className="w-6 h-6 animate-spin" />
            <div className="text-sm">
              Loading Swagger UI and fetching{" "}
              <code className="text-xs bg-[var(--surface-3)] px-1 py-0.5 rounded">
                {OPENAPI_URL}
              </code>
              …
            </div>
          </div>
        )}
 
        {status === "error" && (
          <div className="rounded-lg border border-red-500/40 bg-red-500/10 p-6 text-sm">
            <div className="flex items-start gap-3 text-red-400">
              <AlertCircle className="w-5 h-5 mt-0.5 flex-shrink-0" />
              <div>
                <div className="font-semibold mb-1">
                  Swagger UI failed to load
                </div>
                <div className="text-[var(--text-secondary)] mb-2">
                  {errorMsg}
                </div>
                <div className="text-xs text-[var(--text-secondary)]">
                  Check your network connection or browser console, or download
                  the raw spec via the button above and open it in a local
                  Swagger Editor.
                </div>
              </div>
            </div>
          </div>
        )}
 
        <div
          ref={containerRef}
          id="swagger-ui"
          className={
            status === "ready"
              ? "rounded-lg border border-[var(--border)] bg-white text-black overflow-hidden swagger-host"
              : "hidden"
          }
        />
      </div>
    </div>
  );
}