about summary refs log tree commit diff
path: root/src/state/models/ui/search.ts
blob: 91e1b24bfd02bd2237d561eb2de6bf5fe9737c89 (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
import {makeAutoObservable, runInAction} from 'mobx'
import {searchProfiles, searchPosts} from 'lib/api/search'
import {AppBskyActorProfile as Profile} from '@atproto/api'
import {RootStoreModel} from '../root-store'

export class SearchUIModel {
  isPostsLoading = false
  isProfilesLoading = false
  query: string = ''
  postUris: string[] = []
  profiles: Profile.View[] = []

  constructor(public rootStore: RootStoreModel) {
    makeAutoObservable(this)
  }

  async fetch(q: string) {
    this.postUris = []
    this.profiles = []
    this.query = q
    if (!q.trim()) {
      return
    }

    this.isPostsLoading = true
    this.isProfilesLoading = true

    const [postsSearch, profilesSearch] = await Promise.all([
      searchPosts(q).catch(_e => []),
      searchProfiles(q).catch(_e => []),
    ])
    runInAction(() => {
      this.postUris = postsSearch?.map(p => `at://${p.user.did}/${p.tid}`) || []
      this.isPostsLoading = false
    })

    let profiles: Profile.View[] = []
    if (profilesSearch?.length) {
      do {
        const res = await this.rootStore.api.app.bsky.actor.getProfiles({
          actors: profilesSearch.splice(0, 25).map(p => p.did),
        })
        profiles = profiles.concat(res.data.profiles)
      } while (profilesSearch.length)
    }
    runInAction(() => {
      this.profiles = profiles
      this.isProfilesLoading = false
    })
  }
}