all files / couch/couch/request/ mixin.js

30% Statements 12/40
5% Branches 1/20
57.14% Functions 4/7
30% Lines 12/40
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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91                  120×                                                             232×                         232×                             232× 232×                   213×          
import Ember from 'ember';
import isAbsoluteURL from '../../util/is-absolute-url';
import { fastboot } from '../../util/computed';
 
const {
  getOwner,
  computed,
  computed: { reads }
} = Ember;
 
const request = () => {
  return computed(function() {
    return getOwner(this).factoryFor('couch:request').create();
  }).readOnly();
};
 
const isFastBoot = () => {
  return reads('_fastboot.isFastBoot').readOnly();
};
 
const AuthSession = 'AuthSession';
 
export default Ember.Mixin.create({
 
  __request: request(),
  _fastboot: fastboot(),
  _isFastBoot: isFastBoot(),
 
  _getFastbootRequestCookie() {
    let cookies = this.get('_fastboot.request.cookies');
    if(!cookies) {
      return;
    }
    let cookie = cookies[AuthSession];
    if(!cookie) {
      return;
    }
    return `${AuthSession}=${encodeURIComponent(cookie)}`;
  },
 
  _setFastbootResponseCookie(cookie) {
    let headers = this.get('_fastboot.response.headers');
    headers.append('set-cookie', cookie);
  },
 
  _willSendRequest(opts) {
    Iif(this.get('_isFastBoot')) {
      let cookie = this._getFastbootRequestCookie();
      if(cookie) {
        opts.headers = opts.headers || {};
        opts.headers.cookie = cookie;
      }
      opts.url = opts.url || '';
      if(!isAbsoluteURL(opts.url)) {
        let request = this.get('_fastboot.request');
        let { protocol, host } = request.getProperties('protocol', 'host');
        opts.url = `${protocol}//${host}${opts.url}`;
      }
    }
    return opts;
  },
 
  _didReceiveResponse(hash) {
    if(this.get('_isFastBoot')) {
      let res = hash.res;
      let cookie = res.headers.get('set-cookie');
      if(cookie) {
        this._setFastbootResponseCookie(cookie);
      }
    }
    return hash;
  },
 
  _request(opts) {
    opts = this._willSendRequest(opts);
    return this.get('__request').send(opts).then(hash => {
      hash = this._didReceiveResponse(hash);
      if(hash.raw) {
        return hash.res;
      }
      return hash.json;
    });
  },
 
  request(opts) {
    return this._request(opts);
  }
 
});