import merge from 'lodash/merge';
import spinner from './spinner';
import m from 'mithril';

export const apiVersion = 2;

const baseUrl = window.lichess.apiEndPoint;

function onSuccess(data) {
  spinner.stop();
  return data;
}

function onError(data) {
  spinner.stop();
  throw data;
}

function xhrConfig(xhr) {
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  xhr.setRequestHeader('Accept', 'application/vnd.lichess.v' + apiVersion + '+json');
  xhr.withCredentials = true;
  xhr.timeout = 8000;
}

// convenient wrapper around m.request
export function request(url, opts, feedback, xhrConf) {

  var cfg = {
    url: baseUrl + url,
    method: 'GET',
    data: { },
    config: xhrConf || xhrConfig,
    deserialize: function(text) {
      try {
        return JSON.parse(text);
      } catch (e) {
        throw { response: { error: 'Cannot read data from the server' }};
      }
    },
    unwrapError: function(response, xhr) {
      return { response, status: xhr.status };
    }
  };
  merge(cfg, opts);

  if (cfg.method === 'GET') {
    cfg.data._ = Date.now();
  }

  const stream = m.request(cfg);

  if (feedback) {
    spinner.spin(document.body);
    return stream
    .run(onSuccess)
    .catch(onError);
  } else {
    return stream;
  }
}

@@ -165,130 +165,8 @@
 t;%0A%0A
-function onSuccess(data) %7B%0A  spinner.stop();%0A  return data;%0A%7D%0A%0Afunction onError(data) %7B%0A  spinner.stop();%0A  throw data;%0A%7D%0A
 %0Afun
@@ -490,113 +490,359 @@
 ) %7B%0A
-%0A  var cfg = %7B%0A    url: baseUrl + url,%0A    method: 'GET',%0A    data: %7B %7D,%0A    config: xhrConf %7C%7C xhrConfig
+  let curXhr;%0A%0A  function onSuccess(data) %7B%0A    spinner.stop();%0A    return data;%0A  %7D%0A%0A  function onError(data) %7B%0A    throw %7B response: data, status: curXhr.status %7D;%0A  %7D%0A%0A  const cfg = %7B%0A    url: baseUrl + url,%0A    method: 'GET',%0A    data: %7B %7D,%0A    config: xhr =%3E %7B%0A      curXhr = xhr;%0A      if (xhrConf) xhrConf(xhr);%0A      else xhrConfig(xhr);%0A    %7D
 ,%0A  
@@ -1024,105 +1024,8 @@
   %7D%0A
-    %7D,%0A    unwrapError: function(response, xhr) %7B%0A      return %7B response, status: xhr.status %7D;%0A
     
@@ -1250,23 +1250,74 @@
  .catch(
-onError
+data =%3E %7B%0A      spinner.stop();%0A      onError(data);%0A    %7D
 );%0A  %7D e
@@ -1339,16 +1339,36 @@
 n stream
+%0A    .catch(onError)
 ;%0A  %7D%0A%7D%0A

Fix xhr error unwrapping