@platform/http
Version:
Tools for working with HTTP.
53 lines (52 loc) • 2.17 kB
JavaScript
import { Subject } from 'rxjs';
import { filter, map, share } from 'rxjs/operators';
import { fetch } from './fetch';
import { fetcher } from './http.fetcher';
export const create = (options = {}) => {
const mergeOptions = (methodOptions = {}) => {
const args = Object.assign(Object.assign(Object.assign({}, options), methodOptions), { headers: Object.assign(Object.assign({}, options.headers), methodOptions.headers) });
const { mode = 'cors', headers } = args;
return { mode, headers };
};
const invoke = (method, args) => {
const { mode, headers } = mergeOptions(args.options);
const { url, data } = args;
return fetcher({ method, url, mode, headers, data, fire, fetch: options.fetch || fetch });
};
const _events$ = new Subject();
const fire = e => _events$.next(e);
const events$ = _events$.pipe(share());
const before$ = _events$.pipe(filter(e => e.type === 'HTTP/before'), map(e => e.payload), share());
const after$ = _events$.pipe(filter(e => e.type === 'HTTP/after'), map(e => e.payload), share());
const http = {
create(options = {}) {
const headers = Object.assign(Object.assign({}, http.headers), options.headers);
return create(Object.assign(Object.assign({}, options), { headers }));
},
events$,
before$,
after$,
get headers() {
return Object.assign({}, options.headers);
},
async head(url, options = {}) {
return invoke('HEAD', { url, options });
},
async get(url, options = {}) {
return invoke('GET', { url, options });
},
async put(url, data, options = {}) {
return invoke('PUT', { url, data, options });
},
async post(url, data, options = {}) {
return invoke('POST', { url, data, options });
},
async patch(url, data, options = {}) {
return invoke('PATCH', { url, data, options });
},
async delete(url, data, options = {}) {
return invoke('DELETE', { url, data, options });
},
};
return http;
};