summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/lib/utils/ajax_cache.js
blob: cf030d613df6c51a165afc51c8c1046152ca0325 (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
class AjaxCache {
  constructor() {
    this.internalStorage = { };
    this.pendingRequests = { };
  }

  get(endpoint) {
    return this.internalStorage[endpoint];
  }

  hasData(endpoint) {
    return Object.prototype.hasOwnProperty.call(this.internalStorage, endpoint);
  }

  remove(endpoint) {
    delete this.internalStorage[endpoint];
  }

  retrieve(endpoint) {
    if (this.hasData(endpoint)) {
      return Promise.resolve(this.get(endpoint));
    }

    let pendingRequest = this.pendingRequests[endpoint];

    if (!pendingRequest) {
      pendingRequest = new Promise((resolve, reject) => {
        // jQuery 2 is not Promises/A+ compatible (missing catch)
        $.ajax(endpoint) // eslint-disable-line promise/catch-or-return
        .then(data => resolve(data),
          (jqXHR, textStatus, errorThrown) => {
            const error = new Error(`${endpoint}: ${errorThrown}`);
            error.textStatus = textStatus;
            reject(error);
          },
        );
      })
      .then((data) => {
        this.internalStorage[endpoint] = data;
        delete this.pendingRequests[endpoint];
      })
      .catch((error) => {
        delete this.pendingRequests[endpoint];
        throw error;
      });

      this.pendingRequests[endpoint] = pendingRequest;
    }

    return pendingRequest.then(() => this.get(endpoint));
  }
}

export default new AjaxCache();