- Cache queries and songs across mobile and web - Show cached content and skeletons during loading - Move shared playback and cache utilities into Convex client
52 lines
1.3 KiB
TypeScript
52 lines
1.3 KiB
TypeScript
import { useAuthToken } from "@convex-dev/auth/react"
|
|
import { createContext, useContext, useMemo, type ReactNode } from "react"
|
|
|
|
import { loadPersistentCache } from "@/lib/persistent-cache"
|
|
|
|
export const ANONYMOUS_CACHE_SCOPE = "anon"
|
|
|
|
const CacheScopeContext = createContext(ANONYMOUS_CACHE_SCOPE)
|
|
|
|
void loadPersistentCache()
|
|
|
|
function userIdFromToken(token: string | null) {
|
|
const payload = token?.split(".")[1]
|
|
if (!payload) {
|
|
return null
|
|
}
|
|
|
|
try {
|
|
const json = atob(payload.replace(/-/g, "+").replace(/_/g, "/"))
|
|
const subject = (JSON.parse(json) as { sub?: unknown }).sub
|
|
return typeof subject === "string" ? (subject.split("|")[0] ?? null) : null
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
/** Namespaces persisted client data by server and signed-in user. */
|
|
export function PersistentCacheProvider({
|
|
serverUrl,
|
|
children,
|
|
}: {
|
|
serverUrl: string
|
|
children: ReactNode
|
|
}) {
|
|
const token = useAuthToken()
|
|
const userId = userIdFromToken(token)
|
|
const scope = useMemo(
|
|
() => (userId ? `${serverUrl}|${userId}` : ANONYMOUS_CACHE_SCOPE),
|
|
[serverUrl, userId]
|
|
)
|
|
|
|
return (
|
|
<CacheScopeContext.Provider value={scope}>
|
|
{children}
|
|
</CacheScopeContext.Provider>
|
|
)
|
|
}
|
|
|
|
export function useCacheScope() {
|
|
return useContext(CacheScopeContext)
|
|
}
|