summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/vue_shared/vue_resource_interceptor.js
blob: 73b9131e5bac1378035cc4a4021ef4084d3ff991 (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
import Vue from 'vue';
import VueResource from 'vue-resource';
import csrf from '../lib/utils/csrf';

Vue.use(VueResource);

// Maintain a global counter for active requests
// see: spec/support/wait_for_requests.rb
Vue.http.interceptors.push((request, next) => {
  window.activeVueResources = window.activeVueResources || 0;
  window.activeVueResources += 1;

  next(() => {
    window.activeVueResources -= 1;
  });
});

// Inject CSRF token and parse headers.
// New Vue Resource version uses Headers, we are expecting a plain object to render pagination
// and polling.
Vue.http.interceptors.push((request, next) => {
  request.headers.set(csrf.headerKey, csrf.token);

  next((response) => {
    // Headers object has a `forEach` property that iterates through all values.
    const headers = {};

    response.headers.forEach((value, key) => {
      headers[key] = value;
    });

    response.headers = headers;
  });
});