Files
MemeStudio/app/api/wx-users/level-progress/route.ts
2026-04-19 14:28:36 +08:00

118 lines
3.1 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/prisma'
import { v4 as uuidv4 } from 'uuid'
export const dynamic = 'force-dynamic'
// PUT /api/wx-users/level-progress - Replace a user's completed levels
export async function PUT(request: NextRequest) {
try {
const session = await auth.api.getSession({
headers: request.headers,
})
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const body = await request.json()
const { userId, levelIds } = body
if (typeof userId !== 'string' || !userId) {
return NextResponse.json({ error: 'userId is required' }, { status: 400 })
}
if (!Array.isArray(levelIds) || !levelIds.every((id) => typeof id === 'string')) {
return NextResponse.json(
{ error: 'levelIds must be an array of strings' },
{ status: 400 }
)
}
const uniqueLevelIds = Array.from(new Set(levelIds))
const [user, levels] = await Promise.all([
prisma.wxUser.findUnique({
where: { id: userId },
select: { id: true },
}),
prisma.level.findMany({
where: { id: { in: uniqueLevelIds } },
select: { id: true },
}),
])
if (!user) {
return NextResponse.json({ error: 'User not found' }, { status: 404 })
}
if (levels.length !== uniqueLevelIds.length) {
return NextResponse.json(
{ error: 'Some levels do not exist' },
{ status: 400 }
)
}
await prisma.$transaction(async (tx) => {
await tx.wxUserLevelProgress.deleteMany({
where: { userId },
})
if (uniqueLevelIds.length > 0) {
await tx.wxUserLevelProgress.createMany({
data: uniqueLevelIds.map((levelId) => ({
id: uuidv4(),
userId,
levelId,
timeSpent: 0,
})),
})
}
})
return NextResponse.json({
success: true,
completedLevelCount: uniqueLevelIds.length,
})
} catch (error) {
console.error('Error updating level progress:', error)
return NextResponse.json(
{ error: 'Failed to update level progress' },
{ status: 500 }
)
}
}
// DELETE /api/wx-users/level-progress - Clear all completed levels for a user
export async function DELETE(request: NextRequest) {
try {
const session = await auth.api.getSession({
headers: request.headers,
})
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const body = await request.json()
const { userId } = body
if (typeof userId !== 'string' || !userId) {
return NextResponse.json({ error: 'userId is required' }, { status: 400 })
}
const result = await prisma.wxUserLevelProgress.deleteMany({
where: { userId },
})
return NextResponse.json({ success: true, deleted: result.count })
} catch (error) {
console.error('Error clearing level progress:', error)
return NextResponse.json(
{ error: 'Failed to clear level progress' },
{ status: 500 }
)
}
}