about summary refs log tree commit diff
path: root/src/state/queries/invites.ts
blob: c42ba29d525f09ae9a8202ec9d6a85c20f88824b (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
import {ComAtprotoServerDefs} from '@atproto/api'
import {useQuery} from '@tanstack/react-query'

import {getAgent} from '#/state/session'
import {STALE} from '#/state/queries'

function isInviteAvailable(invite: ComAtprotoServerDefs.InviteCode): boolean {
  return invite.available - invite.uses.length > 0 && !invite.disabled
}

export type InviteCodesQueryResponse = Exclude<
  ReturnType<typeof useInviteCodesQuery>['data'],
  undefined
>
export function useInviteCodesQuery() {
  return useQuery({
    staleTime: STALE.HOURS.ONE,
    queryKey: ['inviteCodes'],
    queryFn: async () => {
      const res = await getAgent().com.atproto.server.getAccountInviteCodes({})

      if (!res.data?.codes) {
        throw new Error(`useInviteCodesQuery: no codes returned`)
      }

      const available = res.data.codes.filter(isInviteAvailable)
      const used = res.data.codes.filter(code => !isInviteAvailable(code))

      return {
        all: [...available, ...used],
        available,
        used,
      }
    },
  })
}