125 lines
3.1 KiB
TypeScript
125 lines
3.1 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { AppService } from '@/lib/services/database-service'
|
|
|
|
const appService = new AppService()
|
|
|
|
// 添加收藏
|
|
export async function POST(request: NextRequest, { params }: { params: { id: string } }) {
|
|
try {
|
|
const { id: appId } = await params
|
|
const body = await request.json()
|
|
const { userId } = body
|
|
|
|
if (!userId) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '用戶ID不能為空' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// 檢查應用是否存在
|
|
const app = await appService.getAppById(appId)
|
|
if (!app) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '應用不存在' },
|
|
{ status: 404 }
|
|
)
|
|
}
|
|
|
|
// 添加收藏
|
|
const result = await appService.addFavorite(userId, appId)
|
|
|
|
if (result.success) {
|
|
return NextResponse.json({
|
|
success: true,
|
|
message: '收藏成功'
|
|
})
|
|
} else {
|
|
// 如果是重複收藏,返回 409 狀態碼
|
|
const statusCode = result.error === '已經收藏過此應用' ? 409 : 400
|
|
return NextResponse.json(
|
|
{ success: false, error: result.error },
|
|
{ status: statusCode }
|
|
)
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('添加收藏錯誤:', error)
|
|
return NextResponse.json(
|
|
{ success: false, error: '添加收藏時發生錯誤' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|
|
|
|
// 移除收藏
|
|
export async function DELETE(request: NextRequest, { params }: { params: { id: string } }) {
|
|
try {
|
|
const { id: appId } = await params
|
|
const { searchParams } = new URL(request.url)
|
|
const userId = searchParams.get('userId')
|
|
|
|
if (!userId) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '用戶ID不能為空' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// 移除收藏
|
|
const result = await appService.removeFavorite(userId, appId)
|
|
|
|
if (result.success) {
|
|
return NextResponse.json({
|
|
success: true,
|
|
message: '取消收藏成功'
|
|
})
|
|
} else {
|
|
return NextResponse.json(
|
|
{ success: false, error: result.error },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
} catch (error) {
|
|
console.error('移除收藏錯誤:', error)
|
|
return NextResponse.json(
|
|
{ success: false, error: '移除收藏時發生錯誤' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|
|
|
|
// 檢查收藏狀態
|
|
export async function GET(request: NextRequest, { params }: { params: { id: string } }) {
|
|
try {
|
|
const { id: appId } = await params
|
|
const { searchParams } = new URL(request.url)
|
|
const userId = searchParams.get('userId')
|
|
|
|
if (!userId) {
|
|
return NextResponse.json(
|
|
{ success: false, error: '用戶ID不能為空' },
|
|
{ status: 400 }
|
|
)
|
|
}
|
|
|
|
// 檢查收藏狀態
|
|
const isFavorited = await appService.isFavorited(userId, appId)
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
data: {
|
|
isFavorited
|
|
}
|
|
})
|
|
|
|
} catch (error) {
|
|
console.error('檢查收藏狀態錯誤:', error)
|
|
return NextResponse.json(
|
|
{ success: false, error: '檢查收藏狀態時發生錯誤' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|