All files / src/app/api/transfers route.ts

86.04% Statements 37/43
64% Branches 16/25
80% Functions 4/5
90.24% Lines 37/41

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      1x     1x       2x 2x           2x     2x                     3x 3x   3x   3x 1x           2x 2x 2x         1x       1x             2x 2x 2x   2x     2x   2x       1x     4x 4x   4x 4x             4x   4x 1x                     3x                                   3x                           4x           2x   1x   1x 1x      
import { NextRequest, NextResponse } from "next/server";
import { edcClient, EDC_CONTEXT } from "@/lib/edc";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
import { promises as fs } from "fs";
import path from "path";
 
export const dynamic = "force-dynamic";
 
/** Load demo transfers from the bundled mock JSON file. */
async function loadMockTransfers(): Promise<unknown[]> {
  try {
    const mockPath = path.join(
      process.cwd(),
      "public",
      "mock",
      "transfers.json",
    );
    const raw = await fs.readFile(mockPath, "utf-8");
    return JSON.parse(raw) as unknown[];
  } catch {
    return [];
  }
}
 
/**
 * GET /api/transfers?participantId=<id> — List transfers for participant.
 * Returns real transfers from the controlplane merged with demo data.
 * POST /api/transfers — Initiate a data transfer.
 */
 
export async function GET(req: NextRequest) {
  const auth = await requireAuth();
  Iif (isAuthError(auth)) return auth;
 
  const participantId = req.nextUrl.searchParams.get("participantId");
 
  if (!participantId) {
    return NextResponse.json(
      { error: "participantId query parameter is required" },
      { status: 400 },
    );
  }
 
  let realTransfers: unknown[] = [];
  try {
    realTransfers = await edcClient.management<unknown[]>(
      `/v5alpha/participants/${participantId}/transferprocesses/request`,
      "POST",
      { "@context": [EDC_CONTEXT], "@type": "QuerySpec", filterExpression: [] },
    );
    Iif (!Array.isArray(realTransfers)) {
      realTransfers = [];
    }
  } catch (err) {
    console.warn(
      "Controlplane transfer list unavailable, using demo data:",
      err,
    );
  }
 
  // Merge with demo transfers so the FHIR viewer is always demonstrable
  const mockTransfers = await loadMockTransfers();
  const realIds = new Set(
    realTransfers.map((t) => (t as Record<string, unknown>)["@id"]),
  );
  const deduped = mockTransfers.filter(
    (m) => !realIds.has((m as Record<string, unknown>)["@id"]),
  );
  const merged = [...realTransfers, ...deduped];
 
  return NextResponse.json(merged);
}
 
/** Mock agreement IDs follow pattern: agreement-fhir-<type>-<NNN> */
const MOCK_AGREEMENT_RE = /^agreement-fhir-[\w-]+-\d{3}$/;
 
export async function POST(req: NextRequest) {
  const auth = await requireAuth();
  Iif (isAuthError(auth)) return auth;
 
  try {
    const body = await req.json();
    const {
      participantId,
      contractId,
      counterPartyAddress,
      assetId,
      transferType,
    } = body;
 
    if (!participantId || !contractId || !counterPartyAddress) {
      return NextResponse.json(
        {
          error:
            "participantId, contractId, and counterPartyAddress are required",
        },
        { status: 400 },
      );
    }
 
    // Demo-mode: if the contractId is a mock agreement, simulate a
    // successful transfer instead of hitting the real controlplane.
    Iif (MOCK_AGREEMENT_RE.test(contractId)) {
      return NextResponse.json(
        {
          "@type": "TransferProcess",
          "@id": `transfer-demo-${Date.now()}`,
          state: "REQUESTED",
          stateTimestamp: Date.now(),
          type: "CONSUMER",
          contractId,
          assetId: assetId || "",
          transferType: transferType || "HttpData-PULL",
          counterPartyAddress,
          _demo: true,
        },
        { status: 201 },
      );
    }
 
    const transferPayload = {
      "@context": [EDC_CONTEXT],
      "@type": "TransferRequest",
      counterPartyAddress,
      protocol: "dataspace-protocol-http:2025-1",
      contractId,
      assetId: assetId || "",
      transferType: transferType || "HttpData-PULL",
      dataDestination: {
        "@type": "DataAddress",
        type: "HttpProxy",
      },
    };
 
    const result = await edcClient.management(
      `/v5alpha/participants/${participantId}/transferprocesses`,
      "POST",
      transferPayload,
    );
 
    return NextResponse.json(result, { status: 201 });
  } catch (err) {
    console.error("Failed to initiate transfer:", err);
    const detail =
      err instanceof Error ? err.message : "Failed to initiate data transfer";
    return NextResponse.json({ error: detail }, { status: 502 });
  }
}