aboutsummaryrefslogtreecommitdiffstats
path: root/apps/web/app/api/bookmarks/export/route.tsx
blob: aefa76b527f4994a384550f56a91791fe19be223 (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
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
import { api, createContextFromRequest } from "@/server/api/client";

import type { ZBookmark } from "@hoarder/shared/types/bookmarks";
import {
  BookmarkTypes,
  MAX_NUM_BOOKMARKS_PER_PAGE,
} from "@hoarder/shared/types/bookmarks";

function toExportFormat(bookmark: ZBookmark) {
  return {
    createdAt: bookmark.createdAt.toISOString(),
    title:
      bookmark.title ??
      (bookmark.content.type === BookmarkTypes.LINK
        ? bookmark.content.title
        : null),
    tags: bookmark.tags.map((t) => t.name),
    type: bookmark.content.type,
    content: {
      type: bookmark.content.type,
      url:
        bookmark.content.type === BookmarkTypes.LINK
          ? bookmark.content.url
          : undefined,
      text:
        bookmark.content.type === BookmarkTypes.TEXT
          ? bookmark.content.text
          : undefined,
    },
    note: bookmark.note,
  };
}

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,
  };

  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)];
  }

  return new Response(
    JSON.stringify({
      // Exclude asset types for now
      bookmarks: results.filter((b) => b.type !== BookmarkTypes.ASSET),
    }),
    {
      status: 200,
      headers: {
        "Content-type": "application/json",
        "Content-disposition": `attachment; filename="hoarder-export-${new Date().toISOString()}.json"`,
      },
    },
  );
}