From 4def1b5fc5ed091d769936382b101635e587fdbc Mon Sep 17 00:00:00 2001 From: TZGyn Date: Sat, 26 Aug 2023 04:29:16 +0800 Subject: [PATCH] Added bookmark category api route --- app/api/bookmark_category/route.ts | 54 ++++++++++++++++++++++++++++++ types/index.ts | 5 +++ 2 files changed, 59 insertions(+) create mode 100644 app/api/bookmark_category/route.ts diff --git a/app/api/bookmark_category/route.ts b/app/api/bookmark_category/route.ts new file mode 100644 index 0000000..8adeb38 --- /dev/null +++ b/app/api/bookmark_category/route.ts @@ -0,0 +1,54 @@ +import { bookmarkCategorySchema, newBookmarkCategorySchema } from '@/types' +import { NextRequest, NextResponse } from 'next/server' +import { bookmarkCategory } from '@/lib/schema' +import { db } from '@/lib/db' +import { eq } from 'drizzle-orm' +import { cookies } from 'next/headers' +import { getUser } from '@/lib/auth' + +export const POST = async (request: NextRequest) => { + const body = await request.json() + const token = cookies().get('token') + + const session_user = await getUser(token) + + const newBookmarkCategory = newBookmarkCategorySchema.safeParse(body) + + if (newBookmarkCategory.success) { + await db.insert(bookmarkCategory).values({ + ...newBookmarkCategory.data, + userId: session_user ? session_user.id : 0, + }) + + return NextResponse.json({ status: 200 }) + } + + return NextResponse.json(newBookmarkCategory.error) +} + +export const PATCH = async (request: NextRequest) => { + const body = await request.json() + + const updateBookmarkCategory = bookmarkCategorySchema.safeParse(body) + + if (updateBookmarkCategory.success) { + await db + .update(bookmarkCategory) + .set({ ...updateBookmarkCategory.data }) + .where(eq(bookmarkCategory.id, updateBookmarkCategory.data.id)) + + return NextResponse.json({ message: 'Bookmark Updated' }) + } + + return NextResponse.json(updateBookmarkCategory.error) +} + +export const DELETE = async (request: NextRequest) => { + const body = await request.json() + + const bookmarkId = body.bookmarkCategoryId + + await db.delete(bookmarkCategory).where(eq(bookmarkCategory.id, bookmarkId)) + + return NextResponse.json({ message: 'Bookmark Deleted' }) +} diff --git a/types/index.ts b/types/index.ts index d276a4d..73cc044 100644 --- a/types/index.ts +++ b/types/index.ts @@ -28,8 +28,13 @@ const bookmarkCategory = { name: z.string().nonempty(), } +export const newBookmarkCategorySchema = z.object({ + ...bookmarkCategory, +}) + export const bookmarkCategorySchema = z.object({ id: z.number(), + ...bookmarkCategory, }) export const bookmarkCategoryWithBookmarksSchema = z.object({