53 lines
1.3 KiB
TypeScript
53 lines
1.3 KiB
TypeScript
"use client"
|
|
|
|
import { useAuthToken } from "@convex-dev/auth/react"
|
|
import { createContext, ReactNode, useContext, useEffect, useMemo } from "react"
|
|
|
|
import { loadPersistentCache } from "@/lib/persistent-cache"
|
|
|
|
export const ANONYMOUS_CACHE_SCOPE = "anon"
|
|
|
|
const CacheScopeContext = createContext(ANONYMOUS_CACHE_SCOPE)
|
|
|
|
if (typeof window !== "undefined") {
|
|
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 the signed-in user. */
|
|
export function PersistentCacheProvider({ children }: { children: ReactNode }) {
|
|
const token = useAuthToken()
|
|
const scope = useMemo(
|
|
() => userIdFromToken(token) ?? ANONYMOUS_CACHE_SCOPE,
|
|
[token]
|
|
)
|
|
|
|
useEffect(() => {
|
|
void loadPersistentCache()
|
|
}, [])
|
|
|
|
return (
|
|
<CacheScopeContext.Provider value={scope}>
|
|
{children}
|
|
</CacheScopeContext.Provider>
|
|
)
|
|
}
|
|
|
|
export function useCacheScope() {
|
|
return useContext(CacheScopeContext)
|
|
}
|