about summary refs log tree commit diff
path: root/src/lib/api/feed/posts.ts
blob: 33eff5099746444c3193520dc8cb2bdd442748ba (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
import {
  type Agent,
  type AppBskyFeedDefs,
  type AppBskyFeedGetPosts,
} from '@atproto/api'

import {logger} from '#/logger'
import {type FeedAPI, type FeedAPIResponse} from './types'

export class PostListFeedAPI implements FeedAPI {
  agent: Agent
  params: AppBskyFeedGetPosts.QueryParams
  peek: AppBskyFeedDefs.FeedViewPost | null = null

  constructor({
    agent,
    feedParams,
  }: {
    agent: Agent
    feedParams: AppBskyFeedGetPosts.QueryParams
  }) {
    this.agent = agent
    if (feedParams.uris.length > 25) {
      logger.warn(
        `Too many URIs provided - expected 25, got ${feedParams.uris.length}`,
      )
    }
    this.params = {
      uris: feedParams.uris.slice(0, 25),
    }
  }

  async peekLatest(): Promise<AppBskyFeedDefs.FeedViewPost> {
    if (this.peek) return this.peek
    throw new Error('Has not fetched yet')
  }

  async fetch({}: {}): Promise<FeedAPIResponse> {
    const res = await this.agent.app.bsky.feed.getPosts({
      ...this.params,
    })
    if (res.success) {
      this.peek = {post: res.data.posts[0]}
      return {
        feed: res.data.posts.map(post => ({post})),
      }
    }
    return {
      feed: [],
    }
  }
}