summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/repo/repo_service.js
blob: b16640ab4f0fb1d4281a804c0d22e72cb7340da9 (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
import axios from 'axios';
import Store from './repo_store';

const RepoService = {
  url: '',
  options: {
    params: {
      format: 'json',
    },
  },
  richExtensionRegExp: /md/,

  checkCurrentBranchIsCommitable() {
    const url = Store.service.refsUrl;
    return axios.get(url, { params: {
      ref: Store.currentBranch,
      search: Store.currentBranch,
    } });
  },

  buildParams(url = this.url) {
    // shallow clone object without reference
    const params = Object.assign({}, this.options.params);

    if (this.urlIsRichBlob(url)) params.viewer = 'rich';

    return params;
  },

  urlIsRichBlob(url = this.url) {
    const extension = url.split('.').pop();

    return this.richExtensionRegExp.test(extension);
  },

  getContent(url = this.url) {
    const params = this.buildParams(url);

    return axios.get(url, {
      params,
    });
  },

  getBase64Content(url = this.url) {
    const request = axios.get(url, {
      responseType: 'arraybuffer',
    });

    return request.then(response => this.bufferToBase64(response.data));
  },

  bufferToBase64(data) {
    return new Buffer(data, 'binary').toString('base64');
  },

  blobURLtoParentTree(url) {
    const urlArray = url.split('/');
    urlArray.pop();
    const blobIndex = urlArray.indexOf('blob');

    if (blobIndex > -1) urlArray[blobIndex] = 'tree';

    return urlArray.join('/');
  },
};

export default RepoService;