UNPKG

@apollo-orbit/angular

Version:

A full-featured GraphQL client for Angular

67 lines (62 loc) 2.3 kB
import { fromEvent, lastValueFrom, of } from 'rxjs'; import { takeUntil, map, catchError } from 'rxjs/operators'; function takeUntilAborted(signal) { return !signal ? source => source : source => source.pipe(takeUntil(fromEvent(signal, 'abort'))); } const normalizedHeaders = { 'accept': 'Accept', 'content-type': 'Content-Type' }; const makeFetch = (httpClient) => (url, { method, ...config }) => { return lastValueFrom(httpClient.request(method, url, { ...config, headers: normalizeHeaders(config.headers), observe: 'response', responseType: 'text', reportProgress: false, withCredentials: config.credentials === 'include' }).pipe(map(response => getResponse(response)), catchError(error => of(getErrorResponse(error))), takeUntilAborted(config.signal))); }; function getErrorResponse(errorResponse) { const { error, name, message, ...rest } = errorResponse; if (errorResponse.status <= 0) throw new TypeError('Failed to fetch'); return getResponse({ body: error, ...rest }); } function getResponse(response) { const headers = mapHeaders(response.headers); if (typeof Response !== 'function') { // node environment const { ok, status, statusText, url, body } = response; return { ok, status, statusText, url, headers: new Headers(headers), text: () => Promise.resolve(body) }; } else { // browser environment return new Response(response.body, { ...response, headers }); } } function mapHeaders(headers) { if (!headers) return headers; return headers.keys().reduce((acc, key) => ({ ...acc, [key]: headers.get(key) }), {}); } // @apollo/client passes headers in a format that fails angular checks function normalizeHeaders(headers) { if (!headers) return headers; return Object .keys(headers) .reduce((acc, header) => { const normalizedHeader = normalizedHeaders[header]; return normalizedHeader !== undefined ? { ...acc, [normalizedHeader]: headers[header] } : { ...acc, [header]: headers[header] }; }, {}); } /** * Generated bundle index. Do not edit. */ export { makeFetch }; //# sourceMappingURL=apollo-orbit.angular.fetch.mjs.map