mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1import {ChatBskyConvoGetConvoForMembers} from '@atproto/api'
2import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query'
3
4import {logger} from '#/logger'
5import {DM_SERVICE_HEADERS} from '#/state/queries/messages/const'
6import {useAgent} from '#/state/session'
7import {STALE} from '..'
8import {RQKEY as CONVO_KEY} from './conversation'
9
10const RQKEY_ROOT = 'convo-for-user'
11export const RQKEY = (did: string) => [RQKEY_ROOT, did]
12
13export function useGetConvoForMembers({
14 onSuccess,
15 onError,
16}: {
17 onSuccess?: (data: ChatBskyConvoGetConvoForMembers.OutputSchema) => void
18 onError?: (error: Error) => void
19}) {
20 const queryClient = useQueryClient()
21 const agent = useAgent()
22
23 return useMutation({
24 mutationFn: async (members: string[]) => {
25 const {data} = await agent.api.chat.bsky.convo.getConvoForMembers(
26 {members: members},
27 {headers: DM_SERVICE_HEADERS},
28 )
29
30 return data
31 },
32 onSuccess: data => {
33 queryClient.setQueryData(CONVO_KEY(data.convo.id), data.convo)
34 onSuccess?.(data)
35 },
36 onError: error => {
37 logger.error(error)
38 onError?.(error)
39 },
40 })
41}
42
43/**
44 * Gets the conversation ID for a given DID. Returns null if it's not possible to message them.
45 */
46export function useMaybeConvoForUser(did: string) {
47 const agent = useAgent()
48
49 return useQuery({
50 queryKey: RQKEY(did),
51 queryFn: async () => {
52 const convo = await agent.api.chat.bsky.convo
53 .getConvoForMembers({members: [did]}, {headers: DM_SERVICE_HEADERS})
54 .catch(() => ({success: null}))
55
56 if (convo.success) {
57 return convo.data.convo
58 } else {
59 return null
60 }
61 },
62 staleTime: STALE.INFINITY,
63 })
64}