forked from
jollywhoppers.com/witchsky.app
Bluesky app fork with some witchin' additions 馃挮
1import {AtUri, type BskyAgent} from '@atproto/api'
2import {type QueryClient, queryOptions, useQuery} from '@tanstack/react-query'
3
4import {STALE} from '#/state/queries'
5import {useAgent} from '#/state/session'
6import {useUnstableProfileViewCache} from './profile'
7
8const RQKEY_ROOT = 'resolved-did'
9export const RQKEY = (didOrHandle: string) => [RQKEY_ROOT, didOrHandle]
10
11const resolvedDidQueryOptions = (
12 agent: BskyAgent,
13 getUnstableProfile: (did: string) => {did: string} | undefined,
14 didOrHandle: string | undefined,
15) =>
16 queryOptions({
17 staleTime: STALE.HOURS.ONE,
18 queryKey: RQKEY(didOrHandle ?? ''),
19 queryFn: async () => {
20 if (!didOrHandle) return ''
21 // Just return the did if it's already one
22 if (didOrHandle.startsWith('did:')) return didOrHandle
23
24 const res = await agent.resolveHandle({handle: didOrHandle})
25 return res.data.did
26 },
27 initialData: () => {
28 // Return undefined if no did or handle
29 if (!didOrHandle) return
30 const profile = getUnstableProfile(didOrHandle)
31 return profile?.did
32 },
33 enabled: !!didOrHandle,
34 })
35
36export function useResolveUriQuery(uri: string | undefined) {
37 const urip = new AtUri(uri || '')
38 const host = urip.host
39
40 const agent = useAgent()
41 const {getUnstableProfile} = useUnstableProfileViewCache()
42
43 return useQuery({
44 ...resolvedDidQueryOptions(agent, getUnstableProfile, host),
45 select: did => ({
46 did,
47 uri: AtUri.make(did, urip.collection, urip.rkey).toString(),
48 }),
49 })
50}
51
52export function useResolveDidQuery(didOrHandle: string | undefined) {
53 const agent = useAgent()
54 const {getUnstableProfile} = useUnstableProfileViewCache()
55
56 return useQuery(
57 resolvedDidQueryOptions(agent, getUnstableProfile, didOrHandle),
58 )
59}
60
61export function precacheResolvedUri(
62 queryClient: QueryClient,
63 handle: string,
64 did: string,
65) {
66 queryClient.setQueryData<string>(RQKEY(handle), did)
67}