aboutsummaryrefslogtreecommitdiff
path: root/src/services/timeline_fetcher/timeline_fetcher.service.js
blob: b28de9e7c503d9354ee09859c6ba672f1a9b6ff4 (plain)
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
import { camelCase } from 'lodash'

import apiService from '../api/api.service.js'

const update = ({store, statuses, timeline, showImmediately}) => {
  const ccTimeline = camelCase(timeline)

  store.dispatch('setError', { value: false })

  store.dispatch('addNewStatuses', {
    timeline: ccTimeline,
    statuses,
    showImmediately
  })
}

const fetchAndUpdate = ({store, credentials, timeline = 'friends', older = false, showImmediately = false, userId = false}) => {
  const args = { timeline, credentials }
  const rootState = store.rootState || store.state
  const timelineData = rootState.statuses.timelines[camelCase(timeline)]

  if (older) {
    args['until'] = timelineData.minVisibleId
  } else {
    args['since'] = timelineData.maxId
  }

  args['userId'] = userId

  return apiService.fetchTimeline(args)
    .then((statuses) => update({store, statuses, timeline, showImmediately}),
      () => store.dispatch('setError', { value: true }))
}

const startFetching = ({timeline = 'friends', credentials, store, userId = false}) => {
  fetchAndUpdate({timeline, credentials, store, showImmediately: true, userId})
  const boundFetchAndUpdate = () => fetchAndUpdate({ timeline, credentials, store, userId })
  return setInterval(boundFetchAndUpdate, 10000)
}
const timelineFetcher = {
  fetchAndUpdate,
  startFetching
}

export default timelineFetcher