File size: 1,982 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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 },
  );
});