about summary refs log tree commit diff
path: root/src/state/queries/messages/conversation.ts
blob: c322e0c62c8700988fd47a3df7522d778aa701b6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import {BskyAgent} from '@atproto-labs/api'
import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query'

import {RQKEY as ListConvosQueryKey} from '#/state/queries/messages/list-converations'
import {useDmServiceUrlStorage} from '#/screens/Messages/Temp/useDmServiceUrlStorage'
import {useHeaders} from './temp-headers'

const RQKEY_ROOT = 'convo'
export const RQKEY = (convoId: string) => [RQKEY_ROOT, convoId]

export function useConvoQuery(convoId: string) {
  const headers = useHeaders()
  const {serviceUrl} = useDmServiceUrlStorage()

  return useQuery({
    queryKey: RQKEY(convoId),
    queryFn: async () => {
      const agent = new BskyAgent({service: serviceUrl})
      const {data} = await agent.api.chat.bsky.convo.getConvo(
        {convoId},
        {headers},
      )
      return data.convo
    },
  })
}

export function useMarkAsReadMutation() {
  const headers = useHeaders()
  const {serviceUrl} = useDmServiceUrlStorage()
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async ({
      convoId,
      messageId,
    }: {
      convoId: string
      messageId?: string
    }) => {
      const agent = new BskyAgent({service: serviceUrl})
      await agent.api.chat.bsky.convo.updateRead(
        {
          convoId,
          messageId,
        },
        {
          encoding: 'application/json',
          headers,
        },
      )
    },
    onSuccess() {
      queryClient.invalidateQueries({
        queryKey: ListConvosQueryKey,
      })
    },
  })
}