@aspectus/resource
Version:
Composable fetch API interface.
1,180 lines (1,024 loc) • 32 kB
JavaScript
/*!
* resource v0.10.21
* (c) 2023 Alex Tkachenko
* Released under the MIT License.
*/
function _typeof(obj) {
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
/* eslint-disable import/prefer-default-export */
var sameResult = function sameResult(x) {
return x;
};
function isFunction(value) {
return Object.prototype.toString.call(value) === '[object Function]' || typeof value === 'function';
}
function createResource() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
urlGetter = _ref.urlGetter,
_ref$middleware = _ref.middleware,
middleware = _ref$middleware === void 0 ? sameResult : _ref$middleware,
_ref$config = _ref.config,
config = _ref$config === void 0 ? {} : _ref$config,
_ref$headers = _ref.headers,
headers = _ref$headers === void 0 ? {} : _ref$headers,
_ref$fetcher = _ref.fetcher,
fetcher = _ref$fetcher === void 0 ? null : _ref$fetcher;
return function () {
var parameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var body = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var caller = fetcher !== null ? fetcher : fetch;
var prepared = middleware({
parameters: parameters,
body: body,
headers: headers,
config: config
});
return caller(urlGetter(prepared.parameters), _objectSpread2({}, prepared.config, {
headers: prepared.headers,
body: prepared.body
}));
};
}
function _arity(n, fn) {
/* eslint-disable no-unused-vars */
switch (n) {
case 0:
return function () {
return fn.apply(this, arguments);
};
case 1:
return function (a0) {
return fn.apply(this, arguments);
};
case 2:
return function (a0, a1) {
return fn.apply(this, arguments);
};
case 3:
return function (a0, a1, a2) {
return fn.apply(this, arguments);
};
case 4:
return function (a0, a1, a2, a3) {
return fn.apply(this, arguments);
};
case 5:
return function (a0, a1, a2, a3, a4) {
return fn.apply(this, arguments);
};
case 6:
return function (a0, a1, a2, a3, a4, a5) {
return fn.apply(this, arguments);
};
case 7:
return function (a0, a1, a2, a3, a4, a5, a6) {
return fn.apply(this, arguments);
};
case 8:
return function (a0, a1, a2, a3, a4, a5, a6, a7) {
return fn.apply(this, arguments);
};
case 9:
return function (a0, a1, a2, a3, a4, a5, a6, a7, a8) {
return fn.apply(this, arguments);
};
case 10:
return function (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {
return fn.apply(this, arguments);
};
default:
throw new Error('First argument to _arity must be a non-negative integer no greater than ten');
}
}
var _arity_1 = _arity;
function _pipe(f, g) {
return function () {
return g.call(this, f.apply(this, arguments));
};
}
var _pipe_1 = _pipe;
function _isPlaceholder(a) {
return a != null && _typeof(a) === 'object' && a['@@functional/placeholder'] === true;
}
var _isPlaceholder_1 = _isPlaceholder;
/**
* Optimized internal one-arity curry function.
*
* @private
* @category Function
* @param {Function} fn The function to curry.
* @return {Function} The curried function.
*/
function _curry1(fn) {
return function f1(a) {
if (arguments.length === 0 || _isPlaceholder_1(a)) {
return f1;
} else {
return fn.apply(this, arguments);
}
};
}
var _curry1_1 = _curry1;
/**
* Optimized internal two-arity curry function.
*
* @private
* @category Function
* @param {Function} fn The function to curry.
* @return {Function} The curried function.
*/
function _curry2(fn) {
return function f2(a, b) {
switch (arguments.length) {
case 0:
return f2;
case 1:
return _isPlaceholder_1(a) ? f2 : _curry1_1(function (_b) {
return fn(a, _b);
});
default:
return _isPlaceholder_1(a) && _isPlaceholder_1(b) ? f2 : _isPlaceholder_1(a) ? _curry1_1(function (_a) {
return fn(_a, b);
}) : _isPlaceholder_1(b) ? _curry1_1(function (_b) {
return fn(a, _b);
}) : fn(a, b);
}
};
}
var _curry2_1 = _curry2;
/**
* Optimized internal three-arity curry function.
*
* @private
* @category Function
* @param {Function} fn The function to curry.
* @return {Function} The curried function.
*/
function _curry3(fn) {
return function f3(a, b, c) {
switch (arguments.length) {
case 0:
return f3;
case 1:
return _isPlaceholder_1(a) ? f3 : _curry2_1(function (_b, _c) {
return fn(a, _b, _c);
});
case 2:
return _isPlaceholder_1(a) && _isPlaceholder_1(b) ? f3 : _isPlaceholder_1(a) ? _curry2_1(function (_a, _c) {
return fn(_a, b, _c);
}) : _isPlaceholder_1(b) ? _curry2_1(function (_b, _c) {
return fn(a, _b, _c);
}) : _curry1_1(function (_c) {
return fn(a, b, _c);
});
default:
return _isPlaceholder_1(a) && _isPlaceholder_1(b) && _isPlaceholder_1(c) ? f3 : _isPlaceholder_1(a) && _isPlaceholder_1(b) ? _curry2_1(function (_a, _b) {
return fn(_a, _b, c);
}) : _isPlaceholder_1(a) && _isPlaceholder_1(c) ? _curry2_1(function (_a, _c) {
return fn(_a, b, _c);
}) : _isPlaceholder_1(b) && _isPlaceholder_1(c) ? _curry2_1(function (_b, _c) {
return fn(a, _b, _c);
}) : _isPlaceholder_1(a) ? _curry1_1(function (_a) {
return fn(_a, b, c);
}) : _isPlaceholder_1(b) ? _curry1_1(function (_b) {
return fn(a, _b, c);
}) : _isPlaceholder_1(c) ? _curry1_1(function (_c) {
return fn(a, b, _c);
}) : fn(a, b, c);
}
};
}
var _curry3_1 = _curry3;
/**
* Tests whether or not an object is an array.
*
* @private
* @param {*} val The object to test.
* @return {Boolean} `true` if `val` is an array, `false` otherwise.
* @example
*
* _isArray([]); //=> true
* _isArray(null); //=> false
* _isArray({}); //=> false
*/
var _isArray = Array.isArray || function _isArray(val) {
return val != null && val.length >= 0 && Object.prototype.toString.call(val) === '[object Array]';
};
function _isString(x) {
return Object.prototype.toString.call(x) === '[object String]';
}
var _isString_1 = _isString;
/**
* Tests whether or not an object is similar to an array.
*
* @private
* @category Type
* @category List
* @sig * -> Boolean
* @param {*} x The object to test.
* @return {Boolean} `true` if `x` has a numeric length property and extreme indices defined; `false` otherwise.
* @example
*
* _isArrayLike([]); //=> true
* _isArrayLike(true); //=> false
* _isArrayLike({}); //=> false
* _isArrayLike({length: 10}); //=> false
* _isArrayLike({0: 'zero', 9: 'nine', length: 10}); //=> true
*/
var _isArrayLike =
/*#__PURE__*/
_curry1_1(function isArrayLike(x) {
if (_isArray(x)) {
return true;
}
if (!x) {
return false;
}
if (_typeof(x) !== 'object') {
return false;
}
if (_isString_1(x)) {
return false;
}
if (x.nodeType === 1) {
return !!x.length;
}
if (x.length === 0) {
return true;
}
if (x.length > 0) {
return x.hasOwnProperty(0) && x.hasOwnProperty(x.length - 1);
}
return false;
});
var _isArrayLike_1 = _isArrayLike;
var XWrap =
/*#__PURE__*/
function () {
function XWrap(fn) {
this.f = fn;
}
XWrap.prototype['@@transducer/init'] = function () {
throw new Error('init not implemented on XWrap');
};
XWrap.prototype['@@transducer/result'] = function (acc) {
return acc;
};
XWrap.prototype['@@transducer/step'] = function (acc, x) {
return this.f(acc, x);
};
return XWrap;
}();
function _xwrap(fn) {
return new XWrap(fn);
}
var _xwrap_1 = _xwrap;
/**
* Creates a function that is bound to a context.
* Note: `R.bind` does not provide the additional argument-binding capabilities of
* [Function.prototype.bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).
*
* @func
* @memberOf R
* @since v0.6.0
* @category Function
* @category Object
* @sig (* -> *) -> {*} -> (* -> *)
* @param {Function} fn The function to bind to context
* @param {Object} thisObj The context to bind `fn` to
* @return {Function} A function that will execute in the context of `thisObj`.
* @see R.partial
* @example
*
* const log = R.bind(console.log, console);
* R.pipe(R.assoc('a', 2), R.tap(log), R.assoc('a', 3))({a: 1}); //=> {a: 3}
* // logs {a: 2}
* @symb R.bind(f, o)(a, b) = f.call(o, a, b)
*/
var bind =
/*#__PURE__*/
_curry2_1(function bind(fn, thisObj) {
return _arity_1(fn.length, function () {
return fn.apply(thisObj, arguments);
});
});
var bind_1 = bind;
function _arrayReduce(xf, acc, list) {
var idx = 0;
var len = list.length;
while (idx < len) {
acc = xf['@@transducer/step'](acc, list[idx]);
if (acc && acc['@@transducer/reduced']) {
acc = acc['@@transducer/value'];
break;
}
idx += 1;
}
return xf['@@transducer/result'](acc);
}
function _iterableReduce(xf, acc, iter) {
var step = iter.next();
while (!step.done) {
acc = xf['@@transducer/step'](acc, step.value);
if (acc && acc['@@transducer/reduced']) {
acc = acc['@@transducer/value'];
break;
}
step = iter.next();
}
return xf['@@transducer/result'](acc);
}
function _methodReduce(xf, acc, obj, methodName) {
return xf['@@transducer/result'](obj[methodName](bind_1(xf['@@transducer/step'], xf), acc));
}
var symIterator = typeof Symbol !== 'undefined' ? Symbol.iterator : '@@iterator';
function _reduce(fn, acc, list) {
if (typeof fn === 'function') {
fn = _xwrap_1(fn);
}
if (_isArrayLike_1(list)) {
return _arrayReduce(fn, acc, list);
}
if (typeof list['fantasy-land/reduce'] === 'function') {
return _methodReduce(fn, acc, list, 'fantasy-land/reduce');
}
if (list[symIterator] != null) {
return _iterableReduce(fn, acc, list[symIterator]());
}
if (typeof list.next === 'function') {
return _iterableReduce(fn, acc, list);
}
if (typeof list.reduce === 'function') {
return _methodReduce(fn, acc, list, 'reduce');
}
throw new TypeError('reduce: list must be array or iterable');
}
var _reduce_1 = _reduce;
/**
* Returns a single item by iterating through the list, successively calling
* the iterator function and passing it an accumulator value and the current
* value from the array, and then passing the result to the next call.
*
* The iterator function receives two values: *(acc, value)*. It may use
* [`R.reduced`](#reduced) to shortcut the iteration.
*
* The arguments' order of [`reduceRight`](#reduceRight)'s iterator function
* is *(value, acc)*.
*
* Note: `R.reduce` does not skip deleted or unassigned indices (sparse
* arrays), unlike the native `Array.prototype.reduce` method. For more details
* on this behavior, see:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description
*
* Dispatches to the `reduce` method of the third argument, if present. When
* doing so, it is up to the user to handle the [`R.reduced`](#reduced)
* shortcuting, as this is not implemented by `reduce`.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig ((a, b) -> a) -> a -> [b] -> a
* @param {Function} fn The iterator function. Receives two values, the accumulator and the
* current element from the array.
* @param {*} acc The accumulator value.
* @param {Array} list The list to iterate over.
* @return {*} The final, accumulated value.
* @see R.reduced, R.addIndex, R.reduceRight
* @example
*
* R.reduce(R.subtract, 0, [1, 2, 3, 4]) // => ((((0 - 1) - 2) - 3) - 4) = -10
* // - -10
* // / \ / \
* // - 4 -6 4
* // / \ / \
* // - 3 ==> -3 3
* // / \ / \
* // - 2 -1 2
* // / \ / \
* // 0 1 0 1
*
* @symb R.reduce(f, a, [b, c, d]) = f(f(f(a, b), c), d)
*/
var reduce =
/*#__PURE__*/
_curry3_1(_reduce_1);
var reduce_1 = reduce;
/**
* This checks whether a function has a [methodname] function. If it isn't an
* array it will execute that function otherwise it will default to the ramda
* implementation.
*
* @private
* @param {Function} fn ramda implemtation
* @param {String} methodname property to check for a custom implementation
* @return {Object} Whatever the return value of the method is.
*/
function _checkForMethod(methodname, fn) {
return function () {
var length = arguments.length;
if (length === 0) {
return fn();
}
var obj = arguments[length - 1];
return _isArray(obj) || typeof obj[methodname] !== 'function' ? fn.apply(this, arguments) : obj[methodname].apply(obj, Array.prototype.slice.call(arguments, 0, length - 1));
};
}
var _checkForMethod_1 = _checkForMethod;
/**
* Returns the elements of the given list or string (or object with a `slice`
* method) from `fromIndex` (inclusive) to `toIndex` (exclusive).
*
* Dispatches to the `slice` method of the third argument, if present.
*
* @func
* @memberOf R
* @since v0.1.4
* @category List
* @sig Number -> Number -> [a] -> [a]
* @sig Number -> Number -> String -> String
* @param {Number} fromIndex The start index (inclusive).
* @param {Number} toIndex The end index (exclusive).
* @param {*} list
* @return {*}
* @example
*
* R.slice(1, 3, ['a', 'b', 'c', 'd']); //=> ['b', 'c']
* R.slice(1, Infinity, ['a', 'b', 'c', 'd']); //=> ['b', 'c', 'd']
* R.slice(0, -1, ['a', 'b', 'c', 'd']); //=> ['a', 'b', 'c']
* R.slice(-3, -1, ['a', 'b', 'c', 'd']); //=> ['b', 'c']
* R.slice(0, 3, 'ramda'); //=> 'ram'
*/
var slice =
/*#__PURE__*/
_curry3_1(
/*#__PURE__*/
_checkForMethod_1('slice', function slice(fromIndex, toIndex, list) {
return Array.prototype.slice.call(list, fromIndex, toIndex);
}));
var slice_1 = slice;
/**
* Returns all but the first element of the given list or string (or object
* with a `tail` method).
*
* Dispatches to the `slice` method of the first argument, if present.
*
* @func
* @memberOf R
* @since v0.1.0
* @category List
* @sig [a] -> [a]
* @sig String -> String
* @param {*} list
* @return {*}
* @see R.head, R.init, R.last
* @example
*
* R.tail([1, 2, 3]); //=> [2, 3]
* R.tail([1, 2]); //=> [2]
* R.tail([1]); //=> []
* R.tail([]); //=> []
*
* R.tail('abc'); //=> 'bc'
* R.tail('ab'); //=> 'b'
* R.tail('a'); //=> ''
* R.tail(''); //=> ''
*/
var tail =
/*#__PURE__*/
_curry1_1(
/*#__PURE__*/
_checkForMethod_1('tail',
/*#__PURE__*/
slice_1(1, Infinity)));
var tail_1 = tail;
/**
* Performs left-to-right function composition. The leftmost function may have
* any arity; the remaining functions must be unary.
*
* In some libraries this function is named `sequence`.
*
* **Note:** The result of pipe is not automatically curried.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Function
* @sig (((a, b, ..., n) -> o), (o -> p), ..., (x -> y), (y -> z)) -> ((a, b, ..., n) -> z)
* @param {...Function} functions
* @return {Function}
* @see R.compose
* @example
*
* const f = R.pipe(Math.pow, R.negate, R.inc);
*
* f(3, 4); // -(3^4) + 1
* @symb R.pipe(f, g, h)(a, b) = h(g(f(a, b)))
*/
function pipe() {
if (arguments.length === 0) {
throw new Error('pipe requires at least one argument');
}
return _arity_1(arguments[0].length, reduce_1(_pipe_1, arguments[0], tail_1(arguments)));
}
var pipe_1 = pipe;
/**
* Retrieve the value at a given path.
*
* @func
* @memberOf R
* @since v0.2.0
* @category Object
* @typedefn Idx = String | Int
* @sig [Idx] -> {a} -> a | Undefined
* @param {Array} path The path to use.
* @param {Object} obj The object to retrieve the nested property from.
* @return {*} The data at `path`.
* @see R.prop
* @example
*
* R.path(['a', 'b'], {a: {b: 2}}); //=> 2
* R.path(['a', 'b'], {c: {b: 2}}); //=> undefined
*/
var path =
/*#__PURE__*/
_curry2_1(function path(paths, obj) {
var val = obj;
var idx = 0;
while (idx < paths.length) {
if (val == null) {
return;
}
val = val[paths[idx]];
idx += 1;
}
return val;
});
var path_1 = path;
/**
* Returns a function that when supplied an object returns the indicated
* property of that object, if it exists.
*
* @func
* @memberOf R
* @since v0.1.0
* @category Object
* @sig s -> {s: a} -> a | Undefined
* @param {String} p The property name
* @param {Object} obj The object to query
* @return {*} The value at `obj.p`.
* @see R.path
* @example
*
* R.prop('x', {x: 100}); //=> 100
* R.prop('x', {}); //=> undefined
* R.compose(R.inc, R.prop('x'))({ x: 3 }) //=> 4
*/
var prop =
/*#__PURE__*/
_curry2_1(function prop(p, obj) {
return path_1([p], obj);
});
var prop_1 = prop;
var orderCmp = function orderCmp(a, b) {
return a.order - b.order || a.index - b.index;
};
var transformerTransducer = function transformerTransducer(acc, t) {
return acc.then.apply(acc, t);
};
var ResourceChain =
/*#__PURE__*/
function () {
function ResourceChain(parameters) {
_classCallCheck(this, ResourceChain);
this.parameters = parameters || {};
}
_createClass(ResourceChain, [{
key: "getResource",
value: function getResource() {
if (!this.preparedResource) {
this.preparedResource = createResource(this.getParameters());
}
return this.preparedResource;
}
}, {
key: "getParameters",
value: function getParameters() {
if (!this.preparedParameters) {
this.preparedParameters = _objectSpread2({}, this.parameters, {
middleware: this.getMiddleware()
});
}
return this.preparedParameters;
}
}, {
key: "getMiddleware",
value: function getMiddleware() {
if (this.preparedMiddleware) {
return this.preparedMiddleware;
}
var _this$parameters$midd = this.parameters.middleware,
middleware = _this$parameters$midd === void 0 ? [] : _this$parameters$midd;
this.preparedMiddleware = middleware.length ? pipe_1.apply(this, middleware.sort(orderCmp).map(prop_1('middleware'))) : sameResult;
return this.preparedMiddleware;
}
}, {
key: "getTransformers",
value: function getTransformers() {
if (this.preparedTransformers) {
return this.preparedTransformers;
}
var _this$parameters$tran = this.parameters.transformers,
transformers = _this$parameters$tran === void 0 ? [] : _this$parameters$tran;
this.preparedTransformers = transformers.sort(orderCmp).map(prop_1('args'));
return this.preparedTransformers;
}
/**
* Overrides `urlGetter`.
*
* @param {Function} urlGetter - Function that returns url based on passed
* parameters.
* @returns Resource - New Resource instance with overrided urlGetter.
* @memberof Resource
*/
}, {
key: "url",
value: function url(urlGetter) {
return new this.constructor(_objectSpread2({}, this.parameters, {
urlGetter: urlGetter
}));
}
/**
* Overrides `fetcher`.
*
* @param {Function} fetcher - Function that implements Fetch API.
* @returns Resource - New Resource instance with overrided fetcher.
* @memberof Resource
*/
}, {
key: "fetcher",
value: function fetcher(_fetcher) {
return new this.constructor(_objectSpread2({}, this.parameters, {
fetcher: _fetcher
}));
}
/**
* Adds new middleware to the set of existing middlewares list.
*
* @param {Function} middleware - Middleware that transforms parameters,
* config, body, headers to fit your needs.
* @param {int} order - Middleware execution order. Must be between 0 - 1000.
* Default is 500.
* @returns Resource - New Resource instance with added middleware.
* @memberof Resource
*/
}, {
key: "middleware",
value: function middleware(_middleware) {
var order = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 500;
var previous = this.parameters.middleware || [];
return new this.constructor(_objectSpread2({}, this.parameters, {
middleware: [{
middleware: _middleware,
order: order,
index: previous.length
}].concat(previous)
}));
}
/**
* Adds new transformer to the set of existing transformers list.
*
* @param {Function} then - Transformer that transforms result body.
* @param {Function} catcher - Error catcher.
* @param {int} order - Transformer execution order. Must be between 0 - 1000.
* Default is 500.
* @returns Resource - New Resource instance with added transformer.
* @memberof Resource
*/
}, {
key: "transform",
value: function transform(then, catcher) {
var order = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 500;
var args = [then];
var previous = this.parameters.transformers || [];
if (isFunction(catcher)) {
args.push(catcher);
}
return new this.constructor(_objectSpread2({}, this.parameters, {
transformers: [{
args: args,
order: order,
index: previous.length
}].concat(previous)
}));
}
}, {
key: "merge",
value: function merge(config, key) {
var value = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
var object = value !== null ? _defineProperty({}, key, value) : key;
return new this.constructor(_objectSpread2({}, this.parameters, _defineProperty({}, config, _objectSpread2({}, this.parameters[config], {}, object))));
}
/**
* Object to merge into `config`(Fetch API configuration object).
*
* @param {*} key - Key for a singular change. Or Object with multiple
* key-value pairs.
* @param {*} value - Value for provided key. Or nothing if the first
* argument is Object.
* @returns Resource - New Resource instance with changed Fetch API config.
* @memberof Resource
*/
}, {
key: "config",
value: function config(key, value) {
return this.merge('config', key, value);
}
/**
* Object to merge into `headers` configuration.
*
* @param {*} key - Key for a singular change. Or Object with multiple
* headers.
* @param {string} value - Value for provided key. Or nothing if the first
* argument is Object.
* @returns Resource - New Resource instance with changed headers.
* @memberof Resource
*/
}, {
key: "headers",
value: function headers(key, value) {
return this.merge('headers', key, value);
}
/**
* Make API call to the resource
*
* @param {*} args - Arguments, required to make an API call.
* @returns Promise - Result of the api call.
* @memberof Resource
*/
}, {
key: "makeRequest",
value: function makeRequest() {
var resource = this.getResource();
return resource.apply(this, arguments); // eslint-disable-line prefer-rest-params
}
}, {
key: "applyTransformers",
value: function applyTransformers(promise) {
var transformers = this.getTransformers();
return transformers.reduce(transformerTransducer, promise);
}
/**
* Execute chain
*
* @param {*} args - Arguments, required to make an API call.
* @returns Promise - Transformed result of api call.
* @memberof Resource
*/
}, {
key: "execute",
value: function execute() {
return this.applyTransformers(this.makeRequest.apply(this, arguments) // eslint-disable-line prefer-rest-params
);
}
}]);
return ResourceChain;
}();
/**
* Internal curryN function.
*
* @private
* @category Function
* @param {Number} length The arity of the curried function.
* @param {Array} received An array of arguments received thus far.
* @param {Function} fn The function to curry.
* @return {Function} The curried function.
*/
function _curryN(length, received, fn) {
return function () {
var combined = [];
var argsIdx = 0;
var left = length;
var combinedIdx = 0;
while (combinedIdx < received.length || argsIdx < arguments.length) {
var result;
if (combinedIdx < received.length && (!_isPlaceholder_1(received[combinedIdx]) || argsIdx >= arguments.length)) {
result = received[combinedIdx];
} else {
result = arguments[argsIdx];
argsIdx += 1;
}
combined[combinedIdx] = result;
if (!_isPlaceholder_1(result)) {
left -= 1;
}
combinedIdx += 1;
}
return left <= 0 ? fn.apply(this, combined) : _arity_1(left, _curryN(length, combined, fn));
};
}
var _curryN_1 = _curryN;
/**
* Returns a curried equivalent of the provided function, with the specified
* arity. The curried function has two unusual capabilities. First, its
* arguments needn't be provided one at a time. If `g` is `R.curryN(3, f)`, the
* following are equivalent:
*
* - `g(1)(2)(3)`
* - `g(1)(2, 3)`
* - `g(1, 2)(3)`
* - `g(1, 2, 3)`
*
* Secondly, the special placeholder value [`R.__`](#__) may be used to specify
* "gaps", allowing partial application of any combination of arguments,
* regardless of their positions. If `g` is as above and `_` is [`R.__`](#__),
* the following are equivalent:
*
* - `g(1, 2, 3)`
* - `g(_, 2, 3)(1)`
* - `g(_, _, 3)(1)(2)`
* - `g(_, _, 3)(1, 2)`
* - `g(_, 2)(1)(3)`
* - `g(_, 2)(1, 3)`
* - `g(_, 2)(_, 3)(1)`
*
* @func
* @memberOf R
* @since v0.5.0
* @category Function
* @sig Number -> (* -> a) -> (* -> a)
* @param {Number} length The arity for the returned function.
* @param {Function} fn The function to curry.
* @return {Function} A new, curried function.
* @see R.curry
* @example
*
* const sumArgs = (...args) => R.sum(args);
*
* const curriedAddFourNumbers = R.curryN(4, sumArgs);
* const f = curriedAddFourNumbers(1, 2);
* const g = f(3);
* g(4); //=> 10
*/
var curryN =
/*#__PURE__*/
_curry2_1(function curryN(length, fn) {
if (length === 1) {
return _curry1_1(fn);
}
return _arity_1(length, _curryN_1(length, [], fn));
});
var curryN_1 = curryN;
/**
* Returns a curried equivalent of the provided function. The curried function
* has two unusual capabilities. First, its arguments needn't be provided one
* at a time. If `f` is a ternary function and `g` is `R.curry(f)`, the
* following are equivalent:
*
* - `g(1)(2)(3)`
* - `g(1)(2, 3)`
* - `g(1, 2)(3)`
* - `g(1, 2, 3)`
*
* Secondly, the special placeholder value [`R.__`](#__) may be used to specify
* "gaps", allowing partial application of any combination of arguments,
* regardless of their positions. If `g` is as above and `_` is [`R.__`](#__),
* the following are equivalent:
*
* - `g(1, 2, 3)`
* - `g(_, 2, 3)(1)`
* - `g(_, _, 3)(1)(2)`
* - `g(_, _, 3)(1, 2)`
* - `g(_, 2)(1)(3)`
* - `g(_, 2)(1, 3)`
* - `g(_, 2)(_, 3)(1)`
*
* @func
* @memberOf R
* @since v0.1.0
* @category Function
* @sig (* -> a) -> (* -> a)
* @param {Function} fn The function to curry.
* @return {Function} A new, curried function.
* @see R.curryN, R.partial
* @example
*
* const addFourNumbers = (a, b, c, d) => a + b + c + d;
*
* const curriedAddFourNumbers = R.curry(addFourNumbers);
* const f = curriedAddFourNumbers(1, 2);
* const g = f(3);
* g(4); //=> 10
*/
var curry =
/*#__PURE__*/
_curry1_1(function curry(fn) {
return curryN_1(fn.length, fn);
});
var curry_1 = curry;
var keyMiddleware = curry_1(function (key, partialMiddleware, params) {
return _objectSpread2({}, params, _defineProperty({}, key, partialMiddleware((params || {})[key])));
});
var configMiddleware = keyMiddleware('config');
var parametersMiddleware = keyMiddleware('parameters');
var headersMiddleware = keyMiddleware('headers');
var bodyMiddleware = keyMiddleware('body');
var defaultsMiddleware = function defaultsMiddleware(defaults) {
return function (parameters) {
return _objectSpread2({}, defaults, {}, parameters);
};
};
var overrideMiddleware = function overrideMiddleware(override) {
return function (parameters) {
return _objectSpread2({}, parameters, {}, override);
};
};
var jsonRequestMiddleware = pipe_1(headersMiddleware(overrideMiddleware({
'Content-Type': 'application/json'
})), bodyMiddleware(function (body) {
return typeof body === 'undefined' || body === null ? body : JSON.stringify(body);
}));
var baseResource = new ResourceChain().config({
mode: 'same-origin',
cache: 'default',
credentials: 'same-origin',
redirect: 'follow',
referrer: 'client'
});
var receiveResource = baseResource.config({
method: 'GET'
});
var sendResource = baseResource.config({
method: 'POST'
});
export { ResourceChain, baseResource, bodyMiddleware, configMiddleware, createResource, defaultsMiddleware, headersMiddleware, jsonRequestMiddleware, keyMiddleware, overrideMiddleware, parametersMiddleware, receiveResource, sendResource };