aboutsummaryrefslogtreecommitdiffstats
path: root/src/stores/RequestStore.js
blob: bbfe6f6df271478a87eea7fa3cdcb3e9604b553c (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
import { action, computed, observable } from 'mobx';

import Store from './lib/Store';

const debug = require('debug')('Franz:RequestsStore');

export default class RequestStore extends Store {
  @observable userInfoRequest;
  @observable servicesRequest;
  @observable showRequiredRequestsError = false;

  retries = 0;
  retryDelay = 2000;

  constructor(...args) {
    super(...args);

    this.actions.requests.retryRequiredRequests.listen(this._retryRequiredRequests.bind(this));

    this.registerReactions([
      this._autoRetry.bind(this),
    ]);
  }

  setup() {
    this.userInfoRequest = this.stores.user.getUserInfoRequest;
    this.servicesRequest = this.stores.services.allServicesRequest;
  }

  @computed get areRequiredRequestsSuccessful() {
    return !this.userInfoRequest.isError
      && !this.servicesRequest.isError;
  }

  @computed get areRequiredRequestsLoading() {
    return this.userInfoRequest.isExecuting
      || this.servicesRequest.isExecuting;
  }

  @action _retryRequiredRequests() {
    this.userInfoRequest.reload();
    this.servicesRequest.reload();
  }

  // Reactions
  _autoRetry() {
    const delay = (this.retries <= 10 ? this.retries : 10) * this.retryDelay;
    if (!this.areRequiredRequestsSuccessful && this.stores.user.isLoggedIn) {
      setTimeout(() => {
        this.retries += 1;
        this._retryRequiredRequests();
        if (this.retries === 4) {
          this.showRequiredRequestsError = true;
        }

        this._autoRetry();
        debug(`Retry required requests delayed in ${(delay) / 1000}s`);
      }, delay);
    }
  }
}