mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1import React from 'react'
2import {useMutation, useQueryClient} from '@tanstack/react-query'
3
4import {STALE} from '#/state/queries'
5import {useAgent} from '#/state/session'
6
7const handleQueryKeyRoot = 'handle'
8const fetchHandleQueryKey = (handleOrDid: string) => [
9 handleQueryKeyRoot,
10 handleOrDid,
11]
12const didQueryKeyRoot = 'did'
13const fetchDidQueryKey = (handleOrDid: string) => [didQueryKeyRoot, handleOrDid]
14
15export function useFetchHandle() {
16 const queryClient = useQueryClient()
17 const agent = useAgent()
18
19 return React.useCallback(
20 async (handleOrDid: string) => {
21 if (handleOrDid.startsWith('did:')) {
22 const res = await queryClient.fetchQuery({
23 staleTime: STALE.MINUTES.FIVE,
24 queryKey: fetchHandleQueryKey(handleOrDid),
25 queryFn: () => agent.getProfile({actor: handleOrDid}),
26 })
27 return res.data.handle
28 }
29 return handleOrDid
30 },
31 [queryClient, agent],
32 )
33}
34
35export function useUpdateHandleMutation() {
36 const queryClient = useQueryClient()
37 const agent = useAgent()
38
39 return useMutation({
40 mutationFn: async ({handle}: {handle: string}) => {
41 await agent.updateHandle({handle})
42 },
43 onSuccess(_data, variables) {
44 queryClient.invalidateQueries({
45 queryKey: fetchHandleQueryKey(variables.handle),
46 })
47 },
48 })
49}
50
51export function useFetchDid() {
52 const queryClient = useQueryClient()
53 const agent = useAgent()
54
55 return React.useCallback(
56 async (handleOrDid: string) => {
57 return queryClient.fetchQuery({
58 staleTime: STALE.INFINITY,
59 queryKey: fetchDidQueryKey(handleOrDid),
60 queryFn: async () => {
61 let identifier = handleOrDid
62 if (!identifier.startsWith('did:')) {
63 const res = await agent.resolveHandle({handle: identifier})
64 identifier = res.data.did
65 }
66 return identifier
67 },
68 })
69 },
70 [queryClient, agent],
71 )
72}