open-prompt / src /app /api /star /route.ts
GitHub Action
Automated sync to Hugging Face
bcce530
import { NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { getAuthUser } from '@/lib/auth'
export const dynamic = 'force-dynamic'
// Helper to ensure user exists in database
async function ensureUserExists(userId: string, email?: string, name?: string) {
const existingUser = await prisma.user.findUnique({
where: { id: userId },
})
if (!existingUser) {
await prisma.user.create({
data: {
id: userId,
email: email || `${userId}@stackauth.local`,
name: name || null,
},
})
}
}
// Toggle star on a prompt β€” requires authentication
export async function POST(req: Request) {
try {
// Server-side auth β€” no more trusting client userId
const authUser = await getAuthUser()
if (!authUser) {
return NextResponse.json(
{ error: 'Authentication required' },
{ status: 401 }
)
}
const { promptId } = await req.json()
if (!promptId) {
return NextResponse.json(
{ error: 'promptId is required' },
{ status: 400 }
)
}
// Ensure user exists in database
await ensureUserExists(authUser.id, authUser.email ?? undefined, authUser.displayName ?? undefined)
// Check if already starred
const existingStar = await prisma.star.findUnique({
where: {
userId_promptId: {
userId: authUser.id,
promptId,
},
},
})
if (existingStar) {
// Unstar β€” use transaction to keep count in sync
await prisma.$transaction([
prisma.star.delete({
where: {
userId_promptId: {
userId: authUser.id,
promptId,
},
},
}),
prisma.prompt.update({
where: { id: promptId },
data: { starsCount: { decrement: 1 } },
}),
])
return NextResponse.json({ starred: false })
} else {
// Star β€” use transaction to keep count in sync
await prisma.$transaction([
prisma.star.create({
data: {
userId: authUser.id,
promptId,
},
}),
prisma.prompt.update({
where: { id: promptId },
data: { starsCount: { increment: 1 } },
}),
])
return NextResponse.json({ starred: true })
}
} catch (error) {
console.error('Star error:', error)
return NextResponse.json(
{ error: 'Failed to toggle star' },
{ status: 500 }
)
}
}
// Check if current user has starred a prompt
export async function GET(req: Request) {
try {
const { searchParams } = new URL(req.url)
const promptId = searchParams.get('promptId')
const authUser = await getAuthUser()
if (!promptId || !authUser) {
return NextResponse.json({ starred: false })
}
const star = await prisma.star.findUnique({
where: {
userId_promptId: {
userId: authUser.id,
promptId,
},
},
})
return NextResponse.json({ starred: !!star })
} catch (error) {
console.error('Check star error:', error)
return NextResponse.json({ starred: false })
}
}