UNPKG

@aspectus/superagent-fetch

Version:

Custom fetcher that adapts [superagent](https://github.com/visionmedia/superagent) library to the default Fetch API.

48 lines (42 loc) 1.78 kB
/*! * superagent-fetch v0.10.10 * (c) 2020 Alex Tkachenko * Released under the MIT License. */ import { partial, compose } from 'ramda'; import superagent from 'superagent'; import cancellablePromiseProxy from '@aspectus/cancellable-promise-proxy'; import progressPromiseProxy from '@aspectus/progress-promise-proxy'; var FOLLOW_REDIRECT = 'follow'; var nullHandler = function nullHandler() { return null; }; function createRequestFromFetch(agent, url) { var init = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var _init$method = init.method, method = _init$method === void 0 ? 'GET' : _init$method, _init$headers = init.headers, headers = _init$headers === void 0 ? {} : _init$headers, _init$redirect = init.redirect, redirect = _init$redirect === void 0 ? FOLLOW_REDIRECT : _init$redirect, body = init.body; return agent(method, url).set(headers).redirects(redirect === FOLLOW_REDIRECT ? 5 : 0).send(body); } function makeRequest(agent, proxy, resource) { var init = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var request = createRequestFromFetch(agent, resource, init); // HACK: Forcing progress handling in superagent. // With empty progress handlers list it would not subscribe on actual // progress event at all. request.on('progress', nullHandler); return proxy(new Promise(function (resolve, reject) { return request.then(resolve, reject); }), { request: request, cancelController: request, progressEmitter: request }); } var baseProxy = compose(cancellablePromiseProxy, progressPromiseProxy); var main = partial(makeRequest, [superagent, baseProxy]); export default main; export { baseProxy, createRequestFromFetch, makeRequest };