about summary refs log tree commit diff
path: root/src/state/models/discovery/suggested-posts.ts
blob: 6c8de3023c16e68e8c246816c1c3b8e2bfd6f39a (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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import {makeAutoObservable, runInAction} from 'mobx'
import {RootStoreModel} from '../root-store'
import {PostsFeedItemModel} from '../feeds/posts'
import {cleanError} from 'lib/strings/errors'
import {TEAM_HANDLES} from 'lib/constants'
import {
  getMultipleAuthorsPosts,
  mergePosts,
} from 'lib/api/build-suggested-posts'

export class SuggestedPostsModel {
  // state
  isLoading = false
  hasLoaded = false
  error = ''

  // data
  posts: PostsFeedItemModel[] = []

  constructor(public rootStore: RootStoreModel) {
    makeAutoObservable(
      this,
      {
        rootStore: false,
      },
      {autoBind: true},
    )
  }

  get hasContent() {
    return this.posts.length > 0
  }

  get hasError() {
    return this.error !== ''
  }

  get isEmpty() {
    return this.hasLoaded && !this.hasContent
  }

  // public api
  // =

  async setup() {
    this._xLoading()
    try {
      const responses = await getMultipleAuthorsPosts(
        this.rootStore,
        TEAM_HANDLES(String(this.rootStore.agent.service)),
        undefined,
        30,
      )
      runInAction(() => {
        const finalPosts = mergePosts(responses, {repostsOnly: true})
        // hydrate into models
        this.posts = finalPosts.map((post, i) => {
          // strip the reasons to hide that these are reposts
          delete post.reason
          return new PostsFeedItemModel(this.rootStore, `post-${i}`, post)
        })
      })
      this._xIdle()
    } catch (e: any) {
      this.rootStore.log.error('SuggestedPostsView: Failed to load posts', {
        e,
      })
      this._xIdle() // dont bubble to the user
    }
  }

  // state transitions
  // =

  _xLoading() {
    this.isLoading = true
    this.error = ''
  }

  _xIdle(err?: any) {
    this.isLoading = false
    this.hasLoaded = true
    this.error = cleanError(err)
    if (err) {
      this.rootStore.log.error('Failed to fetch suggested posts', err)
    }
  }
}