summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/subbable_resource.js.es6
blob: d81916051284986d5a7bd115d093a1b02abe5a8e (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
(() => {
/*
*   SubbableResource can be extended to provide a pubsub-style service for one-off REST
*   calls. Subscribe by passing a callback or render method you will use to handle responses.
 *
* */

  class SubbableResource {
    constructor(resourcePath) {
      this.endpoint = resourcePath;

      // TODO: Switch to axios.create
      this.resource = $.ajax;
      this.subscribers = [];
    }

    subscribe(callback) {
      this.subscribers.push(callback);
    }

    publish(newResponse) {
      const responseCopy = _.extend({}, newResponse);
      this.subscribers.forEach((fn) => {
        fn(responseCopy);
      });
      return newResponse;
    }

    get(payload) {
      return this.resource(payload)
        .then(data => this.publish(data));
    }

    post(payload) {
      return this.resource(payload)
        .then(data => this.publish(data));
    }

    put(payload) {
      return this.resource(payload)
        .then(data => this.publish(data));
    }

    delete(payload) {
      return this.resource(payload)
        .then(data => this.publish(data));
    }
  }

  gl.SubbableResource = SubbableResource;
})(window.gl || (window.gl = {}));