Files
spsays-training/app/api/search/users/route.ts
T

63 lines
1.8 KiB
TypeScript

/**
* Same-origin proxy for the user-search endpoint.
*
* Pattern mirrors /api/search (content search) — the browser can't talk
* to BFF_URL directly (server-only env var; no NEXT_PUBLIC_ prefix), so
* the search page fetches this same-origin route and we proxy through
* to /api/v1/users/search server-side. Returned payload is sanitized
* by the BFF (handle / name / avatar_url only — no email, role, plan).
*/
import { NextRequest, NextResponse } from "next/server";
const BFF_BASE = process.env.BFF_URL || "http://localhost:8080";
type EmptyShape = {
query: string;
results: Array<{ handle: string; name: string; avatar_url: string | null }>;
total: number;
page: number;
limit: number;
total_pages: number;
};
const empty = (q: string): EmptyShape => ({
query: q,
results: [],
total: 0,
page: 1,
limit: 20,
total_pages: 0,
});
export async function GET(request: NextRequest) {
const { searchParams } = request.nextUrl;
const q = (searchParams.get("q") || "").trim();
const limit = searchParams.get("limit") || "20";
const page = searchParams.get("page") || "1";
if (!q) {
return NextResponse.json(empty(""));
}
try {
const url = new URL("/api/v1/users/search", BFF_BASE);
url.searchParams.set("q", q);
url.searchParams.set("limit", limit);
url.searchParams.set("page", page);
const res = await fetch(url.toString(), {
headers: { Accept: "application/json" },
});
if (!res.ok) {
return NextResponse.json(empty(q), { status: res.status });
}
const data = await res.json();
// Unwrap BFF envelope: { data: { query, results } } → { query, results }
const payload = data.data ?? data;
return NextResponse.json(payload);
} catch {
return NextResponse.json(empty(q), { status: 502 });
}
}