about summary refs log tree commit diff
path: root/src/state/queries/messages/conversation.ts
blob: 551fbe98ef1f75bccd80e7972837a74661c2a8ee (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
import {BskyAgent} from '@atproto-labs/api'
import {useMutation, useQuery} from '@tanstack/react-query'

import {useOnMarkAsRead} 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 onMarkAsRead = useOnMarkAsRead()

  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(_, {convoId}) {
      onMarkAsRead(convoId)
    },
  })
}