aboutsummaryrefslogtreecommitdiffstats
path: root/packages/web/lib/services/links.ts
blob: d273b11843ba9a9870d200db82fb4026f9a8aed0 (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
70
71
72
73
74
75
76
77
78
import { LinkCrawlerQueue } from "@remember/shared/queues";
import prisma from "@remember/db";
import { ZBookmarkedLink } from "@/lib/types/api/links";

const defaultLinkFields = {
  id: true,
  url: true,
  createdAt: true,
  details: {
    select: {
      title: true,
      description: true,
      imageUrl: true,
      favicon: true,
    },
  },
  tags: {
    include: {
      tag: true,
    },
  },
};

async function dummyPrismaReturnType() {
  return await prisma.bookmarkedLink.findFirstOrThrow({
    select: defaultLinkFields,
  });
}

function toZodSchema(
  link: Awaited<ReturnType<typeof dummyPrismaReturnType>>,
): ZBookmarkedLink {
  return {
    id: link.id,
    url: link.url,
    createdAt: link.createdAt,
    details: link.details,
    tags: link.tags.map((t) => t.tag),
  };
}

export async function unbookmarkLink(linkId: string, userId: string) {
  await prisma.bookmarkedLink.delete({
    where: {
      id: linkId,
      userId,
    },
  });
}

export async function bookmarkLink(url: string, userId: string) {
  const link = await prisma.bookmarkedLink.create({
    data: {
      url,
      userId,
    },
    select: defaultLinkFields,
  });

  // Enqueue crawling request
  await LinkCrawlerQueue.add("crawl", {
    linkId: link.id,
    url: link.url,
  });

  return toZodSchema(link);
}

export async function getLinks(userId: string) {
  return (
    await prisma.bookmarkedLink.findMany({
      where: {
        userId,
      },
      select: defaultLinkFields,
    })
  ).map(toZodSchema);
}