import { NextResponse } from "next/server"; import { z } from "zod"; import { db } from "@/lib/db"; // get gweets export async function GET(request: Request) { const { searchParams } = new URL(request.url); const type = searchParams.get("type") || undefined; const id = searchParams.get("id") || undefined; const cursorQuery = searchParams.get("cursor") || undefined; const take = Number(searchParams.get("limit")) || 20; const skip = cursorQuery ? 1 : 0; const cursor = cursorQuery ? { id: cursorQuery } : undefined; try { const gweets = await db.gweet.findMany({ skip, take, cursor, where: { ...(type === "comments" && { replyToGweetId: id, }), ...(type === "search" && { text: { contains: id, mode: "insensitive", }, }), ...(type === "user_gweets" && { authorId: id, }), ...(type === "user_replies" && { authorId: id, NOT: { replyToGweetId: null, }, }), ...(type === "user_likes" && { likes: { some: { userId: id, }, }, }), }, include: { author: true, likes: true, media: true, regweets: true, quote: { include: { author: true, media: true, }, }, allComments: true, allQuotes: true, }, orderBy: { createdAt: "desc", }, }); const nextId = gweets.length < take ? undefined : gweets[gweets.length - 1].id; return NextResponse.json({ gweets, nextId }); } catch (error) { return NextResponse.error(); } } // create gweet export async function POST(request: Request) { const gweet = await request.json(); const gweetSchema = z .object({ content: z.string().min(1).max(280), authorId: z.string().cuid(), replyToGweetId: z.string().cuid().optional(), quoteGweetId: z.string().cuid().optional(), }) .strict(); const zod = gweetSchema.safeParse(gweet); if (!zod.success) { return NextResponse.json( { message: "Invalid request body", error: zod.error.formErrors, }, { status: 400 }, ); } try { const created_gweet = await db.gweet.create({ data: { ...gweet, }, }); return NextResponse.json(created_gweet, { status: 200 }); } catch (error: any) { return NextResponse.json( { message: "Something went wrong", error: error.message, }, { status: error.errorCode || 500 }, ); } } // delete gweet export async function DELETE(request: Request) { const { searchParams } = new URL(request.url); const id = searchParams.get("id") as string; const idSchema = z.string().cuid(); const zod = idSchema.safeParse(id); if (!zod.success) { return NextResponse.json( { message: "Invalid request body", error: zod.error.formErrors, }, { status: 400 }, ); } try { await db.gweet.delete({ where: { id, }, }); return NextResponse.json({ message: "Gweet deleted successfully", }); } catch (error: any) { return NextResponse.json( { message: "Something went wrong", error: error.message, }, { status: error.errorCode || 500 }, ); } }