import fetch from 'unfetch';

/**
 * Check Status and request courtesy of feathers-rest
 * See https://github.com/feathersjs/feathers-rest/blob/master/src/client/fetch.js
 */
function checkStatus(response) {
  if (response.ok) {
    return response;
  }

  return Promise.resolve()
    .then(() => response.json())
    .then(error => {
      error.code = error.code || response.status;
      error.statusText = error.statusText || response.statusText;
      return Promise.reject(error);
    });
}

function request(options) {
  let fetchOptions = Object.assign({}, options);

  fetchOptions.headers = Object.assign({
    Accept: 'application/json',
  }, fetchOptions.headers);

  if (options.body) {
    fetchOptions.body = JSON.stringify(options.body);
    fetchOptions.headers = Object.assign({
      'Content-Type': 'application/json'
    }, fetchOptions.headers);
  }

  return fetch(options.url, fetchOptions)
      .then(checkStatus)
      .then(response => response.status === 204 ? null : response.json());
}

function requestWithToken(options) {
  let token = options.token;

  if (token) {
    options.headers = Object.assign({
      'Authorization': `Bearer ${token}`
    }, options.headers);
  }

  return request(options);
}

export default {
  get(url, options) {
    return request(Object.assign({ method: 'GET' }, options, { url }));
  },

  post(url, options) {
    return requestWithToken(Object.assign({ method: 'POST' }, options, { url }));
  },

  put(url, options) {
    return requestWithToken(Object.assign({ method: 'PUT' }, options, { url }));
  },

  delete(url, options) {
    return requestWithToken(Object.assign({ method: 'DELETE' }, options, { url }));
  }
}

@@ -201,16 +201,38 @@
 onse) %7B%0A
+  let rejectAsError;%0A%0A
   if (re
@@ -278,114 +278,120 @@
   re
-turn Promise.resolve()%0A    .then(() =%3E response.json())%0A    .then(error =%3E %7B%0A      error.code = error.code
+jectAsError = (body = %7B%7D) =%3E %7B%0A    let code = body.code %7C%7C response.status,%0A        statusText = body.statusText
  %7C%7C 
@@ -405,18 +405,24 @@
 e.status
-;%0A
+Text,%0A  
       er
@@ -428,21 +428,61 @@
 rror
-.statusText =
+ = new Error(statusText);%0A%0A    error.code = code;%0A   
  err
@@ -491,36 +491,26 @@
 .statusText 
-%7C%7C response.
+= 
 statusText;%0A
@@ -509,18 +509,17 @@
 usText;%0A
-  
+%0A
     retu
@@ -546,19 +546,217 @@
 ror);%0A  
+%7D%0A%0A  return Promise.resolve()%0A    .then(() =%3E response.json())%0A    .then(%0A      (body) =%3E rejectAsError(body),%0A      () =%3E rejectAsError(%7B code: response.status, statusText: response.statusText %7D)%0A  
   
-%7D
 );%0A%7D%0A%0Afu

Make sure client deals with JSON parse errors