aboutsummaryrefslogtreecommitdiff
path: root/src/modules/api.js
blob: 95782e3855ae4bf4759552faa8fc4af361e8e624 (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
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
import backendInteractorService from '../services/backend_interactor_service/backend_interactor_service.js'
import { isArray } from 'lodash'
import { Socket } from 'phoenix'

const api = {
  state: {
    backendInteractor: backendInteractorService(),
    fetchers: {},
    socket: null,
    chatDisabled: false,
    followRequests: []
  },
  mutations: {
    setBackendInteractor (state, backendInteractor) {
      state.backendInteractor = backendInteractor
    },
    addFetcher (state, {timeline, fetcher}) {
      state.fetchers[timeline] = fetcher
    },
    removeFetcher (state, {timeline}) {
      delete state.fetchers[timeline]
    },
    setWsToken (state, token) {
      state.wsToken = token
    },
    setSocket (state, socket) {
      state.socket = socket
    },
    setChatDisabled (state, value) {
      state.chatDisabled = value
    },
    setFollowRequests (state, value) {
      state.followRequests = value
    }
  },
  actions: {
    startFetching (store, payload) {
      let userId = false
      let timeline = 'friends'
      let tag = false

      if (isArray(payload)) {
        // For user timelines
        timeline = payload[0]
        userId = payload[1]
      } else if (payload.tag) {
        // For tag timelines
        timeline = 'tag'
        tag = payload.tag
      }

      // Don't start fetching if we already are.
      if (!store.state.fetchers[timeline]) {
        const fetcher = store.state.backendInteractor.startFetching({timeline, store, userId, tag})
        store.commit('addFetcher', {timeline, fetcher})
      }
    },
    stopFetching (store, timeline) {
      const fetcher = store.state.fetchers[timeline]
      window.clearInterval(fetcher)
      store.commit('removeFetcher', {timeline})
    },
    setWsToken (store, token) {
      store.commit('setWsToken', token)
    },
    initializeSocket (store) {
      // Set up websocket connection
      if (!store.state.chatDisabled) {
        const token = store.state.wsToken
        const socket = new Socket('/socket', {params: {token}})
        socket.connect()
        store.dispatch('initializeChat', socket)
      }
    },
    disableChat (store) {
      store.commit('setChatDisabled', true)
    },
    removeFollowRequest (store, request) {
      let requests = store.state.followRequests.filter((it) => it !== request)
      store.commit('setFollowRequests', requests)
    }
  }
}

export default api