aboutsummaryrefslogtreecommitdiffstats
path: root/apps/web/lib/exportBookmarks.ts
blob: dd1913fb9fa020482f9f0210c5d0bae24054cc76 (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
import { z } from "zod";

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

export const zExportBookmarkSchema = z.object({
  createdAt: z.number(),
  title: z.string().nullable(),
  tags: z.array(z.string()),
  content: z
    .discriminatedUnion("type", [
      z.object({
        type: z.literal(BookmarkTypes.LINK),
        url: z.string(),
      }),
      z.object({
        type: z.literal(BookmarkTypes.TEXT),
        text: z.string(),
      }),
    ])
    .nullable(),
  note: z.string().nullable(),
});

export const zExportSchema = z.object({
  bookmarks: z.array(zExportBookmarkSchema),
});

export function toExportFormat(
  bookmark: ZBookmark,
): z.infer<typeof zExportBookmarkSchema> {
  let content = null;
  switch (bookmark.content.type) {
    case BookmarkTypes.LINK: {
      content = {
        type: bookmark.content.type,
        url: bookmark.content.url,
      };
      break;
    }
    case BookmarkTypes.TEXT: {
      content = {
        type: bookmark.content.type,
        text: bookmark.content.text,
      };
      break;
    }
    // Exclude asset types for now
  }
  return {
    createdAt: Math.floor(bookmark.createdAt.getTime() / 1000),
    title:
      bookmark.title ??
      (bookmark.content.type === BookmarkTypes.LINK
        ? bookmark.content.title ?? null
        : null),
    tags: bookmark.tags.map((t) => t.name),
    content,
    note: bookmark.note ?? null,
  };
}