@aspectus/superagent-fetch
Version:
Custom fetcher that adapts [superagent](https://github.com/visionmedia/superagent) library to the default Fetch API.
43 lines (35 loc) • 1.23 kB
JavaScript
import { partial, compose } from 'ramda';
import superagent from 'superagent';
import cancellablePromiseProxy from '@aspectus/cancellable-promise-proxy';
import progressPromiseProxy from '@aspectus/progress-promise-proxy';
const FOLLOW_REDIRECT = 'follow';
const nullHandler = () => null;
export function createRequestFromFetch(agent, url, init = {}) {
const {
method = 'GET',
headers = {},
redirect = FOLLOW_REDIRECT,
body,
} = init;
return agent(method, url)
.set(headers)
.redirects(redirect === FOLLOW_REDIRECT ? 5 : 0)
.send(body);
}
export function makeRequest(agent, proxy, resource, init = {}) {
const 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((resolve, reject) => request.then(resolve, reject)),
{
request,
cancelController: request,
progressEmitter: request,
}
);
}
export const baseProxy = compose(cancellablePromiseProxy, progressPromiseProxy);
export default partial(makeRequest, [superagent, baseProxy]);