route.ts
基本信息
- 类型: API 路由
- 路径:
./src/app/api/collection/route.ts - 路由:
/api/collection
概述
用户收藏接口。支持获取收藏列表、添加收藏和移除收藏。
HTTP 方法
- GET: 获取收藏列表
- POST: 添加收藏
- DELETE: 移除收藏
GET - 获取收藏列表
响应
成功 (200)
{
"collections": [
{
"id": "collection_id",
"userId": "user_id",
"promptId": "prompt_id",
"createdAt": "2024-01-01T00:00:00Z",
"prompt": {
"id": "prompt_id",
"title": "Prompt 标题",
"slug": "prompt-title",
"author": { ... },
"category": { ... },
"tags": [ ... ],
"_count": {
"votes": 10,
"contributors": 2
}
}
}
]
}
未授权 (401)
{
"error": "Unauthorized"
}
POST - 添加收藏
Body 参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| promptId | string | 是 | Prompt ID |
响应
成功 (200)
{
"collection": {
"id": "collection_id",
"userId": "user_id",
"promptId": "prompt_id",
"createdAt": "2024-01-01T00:00:00Z"
},
"added": true
}
错误
未授权 (401)
{
"error": "Unauthorized"
}
已存在 (400)
{
"error": "Already in collection"
}
未找到 (404)
{
"error": "Prompt not found"
}
无法收藏私有 (403)
{
"error": "Cannot add private prompt"
}
验证失败 (400)
{
"error": "Invalid input"
}
DELETE - 移除收藏
Query 参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| promptId | string | 是 | Prompt ID |
响应
成功 (200)
{
"removed": true
}
错误
未授权 (401)
{
"error": "Unauthorized"
}
参数缺失 (400)
{
"error": "promptId required"
}
服务器错误 (500)
{
"error": "Failed to remove from collection"
}
依赖
next/server- Next.js 服务器组件zod- 输入验证@/lib/auth- 认证@/lib/db- Prisma 数据库客户端
权限
- 需要登录
- 用户只能管理自己的收藏
数据模型
收藏使用复合唯一索引 userId_promptId,确保每个用户对每个 Prompt 只能收藏一次。