aboutsummaryrefslogtreecommitdiffstats
path: root/packages/web/app/api/v1/bookmarks/route.ts
blob: 98e01080e89c08adba738d9a150184decd7359a5 (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
import { authOptions } from "@/lib/auth";
import { bookmarkLink, getBookmarks } from "@/lib/services/bookmarks";

import {
  zNewBookmarkRequestSchema,
  ZGetBookmarksResponse,
  ZBookmark,
  zGetBookmarksRequestSchema,
} from "@/lib/types/api/bookmarks";
import { getServerSession } from "next-auth";
import { NextRequest, NextResponse } from "next/server";

export async function POST(request: NextRequest) {
  // TODO: We probably should be using an API key here instead of the session;
  const session = await getServerSession(authOptions);
  if (!session) {
    return new Response(null, { status: 401 });
  }

  const linkRequest = zNewBookmarkRequestSchema.safeParse(await request.json());

  if (!linkRequest.success) {
    return NextResponse.json(
      {
        error: linkRequest.error.toString(),
      },
      { status: 400 },
    );
  }

  const bookmark = await bookmarkLink(linkRequest.data.url, session.user.id);

  const response: ZBookmark = { ...bookmark };
  return NextResponse.json(response, { status: 201 });
}

export async function GET(request: NextRequest) {
  // TODO: We probably should be using an API key here instead of the session;
  const session = await getServerSession(authOptions);
  if (!session) {
    return new Response(null, { status: 401 });
  }

  const query = request.nextUrl.searchParams;
  const params = zGetBookmarksRequestSchema.safeParse(query);

  if (!params.success) {
    return new Response(null, { status: 400 });
  }

  const bookmarks = await getBookmarks(session.user.id, params.data);

  const response: ZGetBookmarksResponse = { bookmarks };
  return NextResponse.json(response);
}