piral-fetch
Version:
Plugin for standardizing fetch in Piral.
43 lines • 1.54 kB
JavaScript
import { httpFetch } from './fetch';
/**
* Creates new Pilet API extensions for fetch.
* @param config The custom fetch configuration, if any.
*/
export function createFetchApi(config = {}) {
return (context) => {
return {
fetch(path, options = {}) {
const originalHeaders = options.headers || {};
const headerPromises = [];
context.emit('before-fetch', {
headers: originalHeaders,
method: options.method || 'GET',
target: path,
setHeaders(headers) {
if (headers) {
headerPromises.push(headers);
}
},
});
return Promise.all(headerPromises)
.then((newHeaders) => {
const headers = newHeaders.reduce((obj, header) => {
if (typeof header === 'object' && header) {
return {
...obj,
...header,
};
}
return obj;
}, originalHeaders);
return {
...options,
headers,
};
})
.then((options) => httpFetch(config, path, options));
},
};
};
}
//# sourceMappingURL=create.js.map