0.0.1.0
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
import { NextRequest, NextResponse } from "next/server"
|
||||
import { getServerSession } from "next-auth"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
import { prisma } from "@/lib/prisma"
|
||||
import { z } from "zod"
|
||||
|
||||
const createTreeSchema = z.object({
|
||||
name: z.string().min(1, "家族树名称不能为空"),
|
||||
description: z.string().optional(),
|
||||
})
|
||||
|
||||
// 获取用户的所有家族树
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions)
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: "未授权" }, { status: 401 })
|
||||
}
|
||||
|
||||
const trees = await prisma.familyTree.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ ownerId: session.user.id },
|
||||
{
|
||||
collaborators: {
|
||||
some: {
|
||||
userId: session.user.id
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
include: {
|
||||
owner: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
}
|
||||
},
|
||||
_count: {
|
||||
select: {
|
||||
members: true,
|
||||
collaborators: true,
|
||||
}
|
||||
}
|
||||
},
|
||||
orderBy: {
|
||||
updatedAt: 'desc'
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({ trees })
|
||||
} catch (error) {
|
||||
console.error("获取家族树失败:", error)
|
||||
return NextResponse.json(
|
||||
{ error: "获取家族树失败" },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 创建新家族树
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions)
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: "未授权" }, { status: 401 })
|
||||
}
|
||||
|
||||
const body = await req.json()
|
||||
const { name, description } = createTreeSchema.parse(body)
|
||||
|
||||
const tree = await prisma.familyTree.create({
|
||||
data: {
|
||||
name,
|
||||
description,
|
||||
ownerId: session.user.id,
|
||||
},
|
||||
include: {
|
||||
owner: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return NextResponse.json({ tree }, { status: 201 })
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return NextResponse.json(
|
||||
{ error: error.errors[0].message },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
console.error("创建家族树失败:", error)
|
||||
return NextResponse.json(
|
||||
{ error: "创建家族树失败" },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user