82 lines
2.2 KiB
TypeScript
82 lines
2.2 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { z } from "zod";
|
|
import { auth } from "@/app/(auth)/auth";
|
|
import { ChatSDKError } from "@/lib/errors";
|
|
import {
|
|
createAgentCategory,
|
|
getVisibleAgentCategories,
|
|
} from "@/lib/db/queries";
|
|
|
|
const scopeSchema = z.enum(["all", "public", "private"]).default("public");
|
|
|
|
const createCategorySchema = z.object({
|
|
name: z.string().trim().min(1).max(64),
|
|
scope: z.enum(["public", "private"]).default("public"),
|
|
});
|
|
|
|
export async function GET(request: NextRequest) {
|
|
try {
|
|
const session = await auth();
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ success: false, error: "未登录" }, { status: 401 });
|
|
}
|
|
|
|
const { searchParams } = new URL(request.url);
|
|
const scope = scopeSchema.parse(searchParams.get("scope") || "public");
|
|
const categories = await getVisibleAgentCategories({
|
|
userId: session.user.id,
|
|
scope,
|
|
});
|
|
|
|
return NextResponse.json({ success: true, data: categories });
|
|
} catch (error) {
|
|
if (error instanceof ChatSDKError) {
|
|
return error.toResponse();
|
|
}
|
|
if (error instanceof z.ZodError) {
|
|
return NextResponse.json(
|
|
{ success: false, error: error.message },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
return NextResponse.json(
|
|
{ success: false, error: "获取智能体分类失败" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|
|
|
|
export async function POST(request: NextRequest) {
|
|
try {
|
|
const session = await auth();
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ success: false, error: "未登录" }, { status: 401 });
|
|
}
|
|
|
|
const body = await request.json();
|
|
const data = createCategorySchema.parse(body);
|
|
|
|
const category = await createAgentCategory({
|
|
userId: session.user.id,
|
|
name: data.name,
|
|
scope: data.scope,
|
|
});
|
|
|
|
return NextResponse.json({ success: true, data: category });
|
|
} catch (error) {
|
|
if (error instanceof ChatSDKError) {
|
|
return error.toResponse();
|
|
}
|
|
if (error instanceof z.ZodError) {
|
|
return NextResponse.json(
|
|
{ success: false, error: error.message },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
return NextResponse.json(
|
|
{ success: false, error: "创建智能体分类失败" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|