Files
otunes/apps/web/lib/server-song.ts
T

47 lines
1.5 KiB
TypeScript

import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server"
import { api } from "@otunes/convex/_generated/api"
import type { Doc, Id } from "@otunes/convex/_generated/dataModel"
import { fetchQuery } from "convex/nextjs"
import { convexServerOptions } from "@/lib/convex-server"
import type { SongSource } from "@/lib/server-hls"
/**
* Loads a song's file paths as the requesting listener, so Convex enforces auth
* even if the proxy is bypassed. Throws when signed out or the song is missing.
*/
export async function getSongSource(id: string): Promise<SongSource> {
const token = await convexAuthNextjsToken()
const song = await fetchQuery(
api.library.getSongSource,
{ id: id as Id<"songs"> },
convexServerOptions(token)
)
if (!song) {
throw new Error("Song not found")
}
return song
}
const SOURCE_BATCH_SIZE = 200
/** `getSongSource` for many songs, in batches. Missing songs are left out. */
export async function getSongSources(
ids: string[]
): Promise<(SongSource & Pick<Doc<"songs">, "album">)[]> {
const token = await convexAuthNextjsToken()
const batches: string[][] = []
for (let start = 0; start < ids.length; start += SOURCE_BATCH_SIZE) {
batches.push(ids.slice(start, start + SOURCE_BATCH_SIZE))
}
const results = await Promise.all(
batches.map((batch) =>
fetchQuery(
api.library.getSongSources,
{ ids: batch as Id<"songs">[] },
convexServerOptions(token)
)
)
)
return results.flat()
}