Skip to content
Snippets Groups Projects
route.ts 3.38 KiB
import { db } from "@/lib/db"
import { getCurrentUser } from "@/lib/session"
import { NextResponse } from "next/server"
import { z } from "zod"

export async function GET(request: Request) {
    const { searchParams } = new URL(request.url)
    const username = searchParams.get("userId") || undefined
    const type = searchParams.get("type") || undefined

    const userIdSchema = z.string().optional()
    const zod = userIdSchema.safeParse(username)

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

    try {
        if (type === "followers") {
            const followers = await db.user
                .findUnique({
                    where: {
                        username,
                    },
                })
                .followers({
                    include: {
                        followers: true,
                        following: true,
                    },
                })
            return NextResponse.json(followers, { status: 200 })
        } else if (type === "following") {
            const following = await db.user
                .findUnique({
                    where: {
                        username,
                    },
                })
                .following({
                    include: {
                        followers: true,
                        following: true,
                    },
                })

            return NextResponse.json(following, { status: 200 })
        }
    } catch (error: any) {
        return NextResponse.json(error.message, { status: 500 })
    }
}

export async function PUT(request: Request) {
    const session = await getCurrentUser()
    const { userId } = await request.json()

    const followerIdSchema = z
        .object({
            userId: z.string().cuid(),
        })
        .strict()

    const zod = followerIdSchema.safeParse({ userId })

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

    try {