WORKFLOW-APP/app/api/bizportal-2/search/route.ts

65 lines
2 KiB
TypeScript
Raw Normal View History

// app/api/bizportal-2/search/route.ts
// POST /api/bizportal-2/search
// Thin wrapper around the Python Playwright sidecar. Synchronous
// — no queue, no polling. The client gets the result in one round
// trip (~5s typical, ~30s worst case for cold login).
import { NextRequest, NextResponse } from "next/server";
export const dynamic = "force-dynamic";
export const maxDuration = 120;
const SERVICE_URL = process.env.BIZPORTAL_SERVICE_URL ?? "http://127.0.0.1:7001";
export async function POST(req: NextRequest) {
const body = await req.json().catch(() => ({}));
const { type, query } = body ?? {};
if (!type || !["id", "ck"].includes(type)) {
return NextResponse.json({ ok: false, error: "type must be 'id' or 'ck'" }, { status: 400 });
}
if (!query?.trim()) {
return NextResponse.json({ ok: false, error: "query is required" }, { status: 400 });
}
const start = Date.now();
try {
const res = await fetch(`${SERVICE_URL}/search`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ type, query: query.trim() }),
// Signal upstream so the browser-side AbortController can cancel.
signal: req.signal,
});
const text = await res.text();
let data: any;
try {
data = JSON.parse(text);
} catch {
return NextResponse.json(
{ ok: false, error: `Python service returned non-JSON: ${text.slice(0, 200)}` },
{ status: 502 },
);
}
if (!res.ok && data.ok === false) {
return NextResponse.json(data, { status: res.status });
}
return NextResponse.json({
...data,
duration_ms: Date.now() - start,
});
} catch (err: any) {
if (err?.name === "AbortError") {
return NextResponse.json({ ok: false, error: "Search cancelled" }, { status: 499 });
}
return NextResponse.json(
{ ok: false, error: `Cannot reach Python service at ${SERVICE_URL}: ${err.message ?? err}` },
{ status: 503 },
);
}
}