- Cache queries and songs across mobile and web - Show cached content and skeletons during loading - Move shared playback and cache utilities into Convex client
55 lines
1.4 KiB
TypeScript
55 lines
1.4 KiB
TypeScript
import {
|
|
getFunctionName,
|
|
type FunctionArgs,
|
|
type FunctionReference,
|
|
type FunctionReturnType,
|
|
} from "convex/server"
|
|
import { convexToJson, type Value } from "convex/values"
|
|
|
|
import { loadPersistentCache, readCache, writeCache } from "./persistent-cache"
|
|
|
|
/** The part of `ConvexReactClient` the cache needs. */
|
|
export type QueryClient = {
|
|
query<Query extends FunctionReference<"query">>(
|
|
query: Query,
|
|
args: FunctionArgs<Query>
|
|
): Promise<FunctionReturnType<Query>>
|
|
}
|
|
|
|
export function queryCacheKey(
|
|
scope: string,
|
|
query: FunctionReference<"query">,
|
|
args: Record<string, unknown>
|
|
) {
|
|
return `q:${scope}:${getFunctionName(query)}:${JSON.stringify(
|
|
convexToJson(args as Value)
|
|
)}`
|
|
}
|
|
|
|
/**
|
|
* Resolves from the persistent cache when possible and refreshes it in the
|
|
* background; only waits on the network for a cold cache.
|
|
*/
|
|
export async function fetchCachedQuery<
|
|
Query extends FunctionReference<"query">,
|
|
>(
|
|
convex: QueryClient,
|
|
scope: string,
|
|
query: Query,
|
|
args: FunctionArgs<Query>
|
|
): Promise<FunctionReturnType<Query>> {
|
|
await loadPersistentCache()
|
|
const key = queryCacheKey(scope, query, args)
|
|
const cached = readCache<FunctionReturnType<Query>>(key)
|
|
const request = convex.query(query, args).then((result) => {
|
|
writeCache(key, result, { notify: true })
|
|
return result
|
|
})
|
|
|
|
if (cached !== undefined) {
|
|
request.catch(() => {})
|
|
return cached
|
|
}
|
|
return request
|
|
}
|