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

71.05% Statements 27/38
30% Branches 3/10
100% Functions 1/1
77.14% Lines 27/35
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                      232× 232× 232×                 232×     232× 232× 232×                 232×       232×   232× 232×     232×   232× 232×       232×     232×   232× 232× 232×   232×           232×          
import Ember from 'ember';
import fetch from 'fetch';
import SofaError from '../../util/error';
import composeURL from '../../util/compose-url';
import wrap from '../../util/wrap-promise';
import { next } from '../../util/run';
 
const {
  RSVP: { reject },
  merge
} = Ember;
 
const raw = opts => {
  let url = opts.url;
  delete opts.url;
  return wrap(fetch(url, opts));
}
 
const rejectResponse = resp => {
  return resp.json().then(json => {
    json.status = resp.status;
    return reject(new SofaError(json));
  });
}
 
const rejectError = err => {
  return reject(new SofaError({ error: 'request', reason: err.message }));
}
 
const ajax = opts => {
  let json = opts.json;
  delete opts.json;
  return raw(opts).then(res => {
    if(res.status >= 400) {
      return rejectResponse(res);
    }
    if(!json) {
      return { res, raw: true };
    }
    return wrap(res.json()).then(json => ({ res, json, raw: false }));
  }, err => {
    return rejectError(err);
  });
}
 
const request = opts => {
  opts = opts || {};
 
  Eif(!Object.hasOwnProperty(opts, 'json')) {
    opts.json = true;
  }
 
  opts.url = composeURL(opts.url, opts.qs);
 
  Eif(opts.json === true) {
    opts.headers = merge({
      'Content-Type': 'application/json',
      'Accept':       'application/json'
    }, opts.headers);
    opts.body = JSON.stringify(opts.body);
  }
 
  delete opts.qs;
 
  opts.mode = 'cors';
  opts.cache = 'default';
  opts.credentials = 'include';
 
  return ajax(opts);
}
 
export default Ember.Object.extend({
 
  send(opts) {
    return request(opts).then(result => next().then(() => result));
  }
 
});