107 const cookieName = "hanko";
108 const bearerToken = Cookies.get(cookieName);
109
110 return new Promise<Response>(function (resolve, reject) {111 const xhr = new XMLHttpRequest();112113 xhr.open(options.method, url, true);114 xhr.setRequestHeader("Accept", "application/json");115 xhr.setRequestHeader("Content-Type", "application/json");116117 if (bearerToken) {118 xhr.setRequestHeader("Authorization", `Bearer ${bearerToken}`);119 }120121 xhr.timeout = timeout;122 xhr.withCredentials = true;123 xhr.onload = () => {124 const authToken = xhr.getResponseHeader("X-Auth-Token");125126 if (authToken) {127 const secure = !!api.match("^https://");128 Cookies.set(cookieName, authToken, { secure });129 }130131 resolve(new Response(xhr));132 };133134 xhr.onerror = () => {135 reject(new TechnicalError());136 };137138 xhr.ontimeout = () => {139 reject(new RequestTimeoutError());140 };141142 xhr.send(options.body ? options.body.toString() : null);143 });144 }
145
146 /**
It is recommended to use arrow functions as callbacks.
Arrow functions can be an attractive alternative to function expressions for callbacks or function arguments.
For example, arrow functions are automatically bound to their surrounding scope/context. This provides an alternative to the pre-ES6 standard of explicitly binding function expressions to achieve similar behavior.
Additionally, arrow functions are:
less verbose, and easier to reason about.
bound lexically regardless of where or when they are invoked.
func(function(a) { return a; }); // ERROR
// prefer: func(a => a)
func(function() { return this.a; }.bind(this)); // ERROR
// prefer: func(() => this.a)
// arrow function callback
func(a => a); // OK
// generator as callback
func(function*() { yield; }); // OK
// function expression not used as callback or function argument
var funcVar = function func(a) { return a; }; // OK
// unbound function expression callback
func(function() { return this.a; }); // OK
// recursive named function callback
func(function recursiveFunc(n) { return n && n + recursiveFunc(n - 1); }); // OK