fetch-auth
Version:
Helper to fetch resources that need authentication
69 lines (57 loc) • 1.83 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.fetchAuth = factory());
}(this, function () { 'use strict';
var babelHelpers = {};
babelHelpers.extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
babelHelpers;
// authorise a user using the Authorization headers on any URI and return the JSON value of
// its response
var index = (function fetchAuth(uri, Authorization) {
var options,
headers,
res,
error,
error,
_arguments = arguments;
return Promise.resolve().then(function () {
options = _arguments.length <= 2 || _arguments[2] === undefined ? {} : _arguments[2];
headers = _arguments.length <= 3 || _arguments[3] === undefined ? {} : _arguments[3];
return fetch(uri, babelHelpers.extends({}, options, {
headers: babelHelpers.extends({
'Content-Type': 'application/json'
}, headers, {
Authorization: Authorization
})
}));
}).then(function (_resp) {
res = _resp;
if (res.status >= 200 && res.status < 300) {
try {
return res.json();
} catch (err) {
error = new Error('Invalid JSON');
error.caught = err;
error.response = res;
throw error;
}
} else {
error = new Error(res.statusText);
error.response = res;
throw error;
}
});
})
return index;
}));