about summary refs log tree commit diff
path: root/src/state/queries/search-posts.ts
blob: e0b317ca9df6822834ce0694168094a0a6e3bfa2 (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
60
61
62
63
64
import {AppBskyFeedDefs, AppBskyFeedSearchPosts} from '@atproto/api'
import {
  useInfiniteQuery,
  InfiniteData,
  QueryKey,
  QueryClient,
} from '@tanstack/react-query'

import {getAgent} from '#/state/session'
import {embedViewRecordToPostView, getEmbeddedPost} from './util'

const searchPostsQueryKey = ({query}: {query: string}) => [
  'search-posts',
  query,
]

export function useSearchPostsQuery({query}: {query: string}) {
  return useInfiniteQuery<
    AppBskyFeedSearchPosts.OutputSchema,
    Error,
    InfiniteData<AppBskyFeedSearchPosts.OutputSchema>,
    QueryKey,
    string | undefined
  >({
    queryKey: searchPostsQueryKey({query}),
    queryFn: async ({pageParam}) => {
      const res = await getAgent().app.bsky.feed.searchPosts({
        q: query,
        limit: 25,
        cursor: pageParam,
      })
      return res.data
    },
    initialPageParam: undefined,
    getNextPageParam: lastPage => lastPage.cursor,
  })
}

export function* findAllPostsInQueryData(
  queryClient: QueryClient,
  uri: string,
): Generator<AppBskyFeedDefs.PostView, undefined> {
  const queryDatas = queryClient.getQueriesData<
    InfiniteData<AppBskyFeedSearchPosts.OutputSchema>
  >({
    queryKey: ['search-posts'],
  })
  for (const [_queryKey, queryData] of queryDatas) {
    if (!queryData?.pages) {
      continue
    }
    for (const page of queryData?.pages) {
      for (const post of page.posts) {
        if (post.uri === uri) {
          yield post
        }
        const quotedPost = getEmbeddedPost(post.embed)
        if (quotedPost?.uri === uri) {
          yield embedViewRecordToPostView(quotedPost)
        }
      }
    }
  }
}