Files
otunes/apps/web/lib/cached-query.ts

52 lines
1.3 KiB
TypeScript

import type { ConvexReactClient } from "convex/react"
import {
getFunctionName,
type FunctionArgs,
type FunctionReference,
type FunctionReturnType,
} from "convex/server"
import { convexToJson, type Value } from "convex/values"
import {
loadPersistentCache,
readCache,
writeCache,
} from "@/lib/persistent-cache"
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: ConvexReactClient,
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
}