aboutsummaryrefslogtreecommitdiffstats
path: root/apps/web/app/api/bookmarks/export/route.tsx
blob: e550fcb5d4692625d857597da41c6ffde79e78f1 (plain) (blame)
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
import { toExportFormat, zExportSchema } from "@/lib/exportBookmarks";
import { api, createContextFromRequest } from "@/server/api/client";
import { z } from "zod";

import { MAX_NUM_BOOKMARKS_PER_PAGE } from "@karakeep/shared/types/bookmarks";

export const dynamic = "force-dynamic";
export async function GET(request: Request) {
  const ctx = await createContextFromRequest(request);
  if (!ctx.user) {
    return Response.json({ error: "Unauthorized" }, { status: 401 });
  }
  const req = {
    limit: MAX_NUM_BOOKMARKS_PER_PAGE,
    useCursorV2: true,
    includeContent: true,
  };

  let resp = await api.bookmarks.getBookmarks(req);
  let results = resp.bookmarks.map(toExportFormat);

  while (resp.nextCursor) {
    resp = await api.bookmarks.getBookmarks({
      ...request,
      cursor: resp.nextCursor,
    });
    results = [...results, ...resp.bookmarks.map(toExportFormat)];
  }

  const exportData: z.infer<typeof zExportSchema> = {
    bookmarks: results.filter((b) => b.content !== null),
  };

  return new Response(JSON.stringify(exportData), {
    status: 200,
    headers: {
      "Content-type": "application/json",
      "Content-disposition": `attachment; filename="karakeep-export-${new Date().toISOString()}.json"`,
    },
  });
}