mirror of https://git.lenooby09.tech/LeNooby09/social-app.git
1import {AppBskyLabelerDefs} from '@atproto/api'
2import {useMutation, useQuery, useQueryClient} from '@tanstack/react-query'
3import {z} from 'zod'
4
5import {labelersDetailedInfoQueryKeyRoot} from '#/lib/react-query'
6import {STALE} from '#/state/queries'
7import {preferencesQueryKey} from '#/state/queries/preferences'
8import {useAgent} from '#/state/session'
9
10const labelerInfoQueryKeyRoot = 'labeler-info'
11export const labelerInfoQueryKey = (did: string) => [
12 labelerInfoQueryKeyRoot,
13 did,
14]
15
16const labelersInfoQueryKeyRoot = 'labelers-info'
17export const labelersInfoQueryKey = (dids: string[]) => [
18 labelersInfoQueryKeyRoot,
19 dids.slice().sort(),
20]
21
22export const labelersDetailedInfoQueryKey = (dids: string[]) => [
23 labelersDetailedInfoQueryKeyRoot,
24 dids,
25]
26
27export function useLabelerInfoQuery({
28 did,
29 enabled,
30}: {
31 did?: string
32 enabled?: boolean
33}) {
34 const agent = useAgent()
35 return useQuery({
36 enabled: !!did && enabled !== false,
37 queryKey: labelerInfoQueryKey(did as string),
38 queryFn: async () => {
39 const res = await agent.app.bsky.labeler.getServices({
40 dids: [did as string],
41 detailed: true,
42 })
43 return res.data.views[0] as AppBskyLabelerDefs.LabelerViewDetailed
44 },
45 })
46}
47
48export function useLabelersInfoQuery({dids}: {dids: string[]}) {
49 const agent = useAgent()
50 return useQuery({
51 enabled: !!dids.length,
52 queryKey: labelersInfoQueryKey(dids),
53 queryFn: async () => {
54 const res = await agent.app.bsky.labeler.getServices({dids})
55 return res.data.views as AppBskyLabelerDefs.LabelerView[]
56 },
57 })
58}
59
60export function useLabelersDetailedInfoQuery({dids}: {dids: string[]}) {
61 const agent = useAgent()
62 return useQuery({
63 enabled: !!dids.length,
64 queryKey: labelersDetailedInfoQueryKey(dids),
65 gcTime: 1000 * 60 * 60 * 6, // 6 hours
66 staleTime: STALE.MINUTES.ONE,
67 queryFn: async () => {
68 const res = await agent.app.bsky.labeler.getServices({
69 dids,
70 detailed: true,
71 })
72 return res.data.views as AppBskyLabelerDefs.LabelerViewDetailed[]
73 },
74 })
75}
76
77export function useLabelerSubscriptionMutation() {
78 const queryClient = useQueryClient()
79 const agent = useAgent()
80
81 return useMutation({
82 async mutationFn({did, subscribe}: {did: string; subscribe: boolean}) {
83 // TODO
84 z.object({
85 did: z.string(),
86 subscribe: z.boolean(),
87 }).parse({did, subscribe})
88
89 if (subscribe) {
90 await agent.addLabeler(did)
91 } else {
92 await agent.removeLabeler(did)
93 }
94 },
95 onSuccess() {
96 queryClient.invalidateQueries({
97 queryKey: preferencesQueryKey,
98 })
99 },
100 })
101}