Skip to content
Snippets Groups Projects
route.ts 1.59 KiB
Newer Older
import { db } from "@/lib/db"
import { getCurrentUser } from "@/lib/session"
import { revalidatePath } from "next/cache"
import { NextRequest, NextResponse } from "next/server"
Caner's avatar
Caner committed

export async function PUT(req: NextRequest) {
Yusuf Akgül's avatar
Yusuf Akgül committed
    const session = await getCurrentUser()
Yusuf Akgül's avatar
Yusuf Akgül committed
    if (!session) {
        return NextResponse.json({ status: 401, message: 'Unauthorized' })
    }

Yusuf Akgül's avatar
Yusuf Akgül committed
    const userId = session.id
    const data = await req.json()
    data.gameId = parseInt(data.gameId)

    try {
        if (data.add) {
            await db.user.update({
                where: {
                    id: userId
                },
                data: {
                    favGameList: {
                        push: data.gameId
                    }
                }
            })
        } else {
            const user = await db.user.findFirst({
                where: {
                    id: userId
                },
                select: {
                    favGameList: true
                },
            })

            await db.user.update({
                where: {
                    id: userId
                },
                data: {
                    favGameList: {
                        set: user?.favGameList.filter((id: number) => id !== data.gameId),
                    }
                }
            })
        }

        const path = req.nextUrl.searchParams.get('path') || '/'
        revalidatePath(path)

        return NextResponse.json({ message: 'Game added' }, { status: 201 })
        return NextResponse.json({ message: error.message }, { status: 500 })
Caner's avatar
Caner committed
}