import { NextRequest, NextResponse } from "next/server"; import { fetchAndExtract, createFromText } from "@/lib/reading/extract"; import { withApiError } from "@/lib/api-error"; /** * POST /api/reading/fetch * * Body: { url: string } | { text: string, title?: string } * * Fetches a URL and extracts readable content, or accepts pasted text. * Returns an article-compatible object for the Reader component. */ export const POST = withApiError(async (request: NextRequest) => { let body: { url?: string; text?: string; title?: string }; try { body = await request.json(); } catch { return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); } const { url, text, title } = body; // URL fetch mode if (url && typeof url === "string") { // Basic URL validation let parsedUrl: URL; try { parsedUrl = new URL(url); } catch { return NextResponse.json({ error: "Invalid URL format" }, { status: 400 }); } if (!["http:", "https:"].includes(parsedUrl.protocol)) { return NextResponse.json( { error: "Only HTTP and HTTPS URLs are supported" }, { status: 400 }, ); } try { const article = await fetchAndExtract(url); return NextResponse.json({ article, source: "url" }); } catch (err) { return NextResponse.json( { error: err instanceof Error ? err.message : "Failed to fetch URL", }, { status: 422 }, ); } } // Paste text mode if (text && typeof text === "string") { try { const article = createFromText(text, title); return NextResponse.json({ article, source: "text" }); } catch (err) { return NextResponse.json( { error: err instanceof Error ? err.message : "Invalid text input", }, { status: 422 }, ); } } return NextResponse.json( { error: "Provide either a 'url' or 'text' field" }, { status: 400 }, ); });