forked from
jollywhoppers.com/witchsky.app
Bluesky app fork with some witchin' additions 馃挮
1import {type AppBskyActorDefs, type AppBskyGraphGetFollows} from '@atproto/api'
2import {
3 type InfiniteData,
4 type QueryClient,
5 type QueryKey,
6 useInfiniteQuery,
7} from '@tanstack/react-query'
8
9import {STALE} from '#/state/queries'
10import {useAgent} from '#/state/session'
11
12const PAGE_SIZE = 30
13type RQPageParam = string | undefined
14
15// TODO refactor invalidate on mutate?
16const RQKEY_ROOT = 'profile-follows'
17export const RQKEY = (did: string) => [RQKEY_ROOT, did]
18
19export function useProfileFollowsQuery(
20 did: string | undefined,
21 {
22 limit,
23 }: {
24 limit?: number
25 } = {
26 limit: PAGE_SIZE,
27 },
28) {
29 const agent = useAgent()
30 return useInfiniteQuery<
31 AppBskyGraphGetFollows.OutputSchema,
32 Error,
33 InfiniteData<AppBskyGraphGetFollows.OutputSchema>,
34 QueryKey,
35 RQPageParam
36 >({
37 staleTime: STALE.MINUTES.ONE,
38 queryKey: RQKEY(did || ''),
39 async queryFn({pageParam}: {pageParam: RQPageParam}) {
40 const res = await agent.app.bsky.graph.getFollows({
41 actor: did || '',
42 limit: limit || PAGE_SIZE,
43 cursor: pageParam,
44 })
45 return res.data
46 },
47 initialPageParam: undefined,
48 getNextPageParam: lastPage => lastPage.cursor,
49 enabled: !!did,
50 })
51}
52
53export function* findAllProfilesInQueryData(
54 queryClient: QueryClient,
55 did: string,
56): Generator<AppBskyActorDefs.ProfileView, void> {
57 const queryDatas = queryClient.getQueriesData<
58 InfiniteData<AppBskyGraphGetFollows.OutputSchema>
59 >({
60 queryKey: [RQKEY_ROOT],
61 })
62 for (const [_queryKey, queryData] of queryDatas) {
63 if (!queryData?.pages) {
64 continue
65 }
66 for (const page of queryData?.pages) {
67 for (const follow of page.follows) {
68 if (follow.did === did) {
69 yield follow
70 }
71 }
72 }
73 }
74}