This repository has been archived on 2026-06-15. You can view files and clone it, but cannot push or open issues or pull requests.
Files
MediaLore/src/app/api/ratings/route.ts
2026-04-21 10:57:08 -04:00

65 lines
2.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { NextRequest, NextResponse } from 'next/server'
import { requireLibraryAccess, requireLibraryWriteAccess } from '@/lib/auth'
import { getDb } from '@/lib/db'
function extractLibraryId(itemKey: string): string | null {
const colonIdx = itemKey.indexOf(':')
if (colonIdx === -1) return null
return itemKey.slice(0, colonIdx)
}
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url)
const itemKey = searchParams.get('itemKey')
if (!itemKey) {
return NextResponse.json({ error: 'itemKey is required' }, { status: 400 })
}
const libraryId = extractLibraryId(itemKey)
if (!libraryId) {
return NextResponse.json({ error: 'Invalid itemKey' }, { status: 400 })
}
const auth = await requireLibraryAccess(request, libraryId)
if (auth instanceof NextResponse) return auth
const db = getDb()
const row = db
.prepare('SELECT user_rating FROM media_items WHERE item_key = ?')
.get(itemKey) as { user_rating: number | null } | undefined
if (!row) {
return NextResponse.json({ error: 'Item not found' }, { status: 404 })
}
return NextResponse.json({ userRating: row.user_rating ?? null })
}
export async function PATCH(request: NextRequest) {
const body = await request.json()
const { itemKey, userRating } = body as { itemKey: string; userRating: number | null }
if (!itemKey) {
return NextResponse.json({ error: 'itemKey is required' }, { status: 400 })
}
if (userRating !== null && (typeof userRating !== 'number' || !Number.isInteger(userRating) || userRating < 1 || userRating > 5)) {
return NextResponse.json({ error: 'userRating must be null or an integer 15' }, { status: 400 })
}
const libraryId = extractLibraryId(itemKey)
if (!libraryId) {
return NextResponse.json({ error: 'Invalid itemKey' }, { status: 400 })
}
const auth = await requireLibraryWriteAccess(request, libraryId)
if (auth instanceof NextResponse) return auth
const db = getDb()
const result = db
.prepare('UPDATE media_items SET user_rating = ? WHERE item_key = ?')
.run(userRating, itemKey)
if (result.changes === 0) {
return NextResponse.json({ error: 'Item not found' }, { status: 404 })
}
return NextResponse.json({ success: true })
}