← back to Norma

app/api/data-explorer/apis/route.ts

70 lines

import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/db';
import { requireRole } from '@/lib/require-role';

/**
 * GET /api/data-explorer/apis
 * Returns discovered APIs from the discovered_apis table.
 * Maps DB column names to the frontend interface:
 *   api_url -> base_url, last_tested_at -> last_checked_at
 */
export async function GET(request: NextRequest) {
  const auth = requireRole(request, 'admin', 'staff');
  if (auth instanceof NextResponse) return auth;

  try {
    const sp = request.nextUrl.searchParams;
    const limit = Math.min(parseInt(sp.get('limit') || '50', 10), 200);
    const offset = parseInt(sp.get('offset') || '0', 10);
    const status = sp.get('status');

    const conditions: string[] = [];
    const params: unknown[] = [];
    let idx = 1;

    if (status) {
      conditions.push(`status = $${idx++}`);
      params.push(status);
    }

    const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';

    params.push(limit, offset);

    const result = await query(
      `SELECT
         id,
         name,
         api_url AS base_url,
         status,
         relevance_score,
         last_tested_at AS last_checked_at,
         description,
         category,
         data_type,
         auth_required,
         created_at
       FROM discovered_apis
       ${where}
       ORDER BY relevance_score DESC NULLS LAST, created_at DESC
       LIMIT $${idx++} OFFSET $${idx++}`,
      params,
    );

    const countResult = await query(
      `SELECT COUNT(*) as total FROM discovered_apis ${where}`,
      params.slice(0, -2),
    );

    return NextResponse.json({
      apis: result.rows,
      total: parseInt(countResult.rows[0]?.total ?? '0', 10),
      limit,
      offset,
    });
  } catch (err) {
    console.error('[data-explorer/apis] GET error:', (err as Error).message);
    return NextResponse.json({ error: 'Failed to load APIs' }, { status: 500 });
  }
}