UNPKG

@graphql-mesh/utils

Version:
53 lines (52 loc) 1.68 kB
import { isPromise } from '@graphql-tools/utils'; import { iterateAsync } from './iterateAsync.js'; export function wrapFetchWithHooks(onFetchHooks) { return function wrappedFetchFn(url, options, context, info) { let fetchFn; const doneHooks = []; function setFetchFn(newFetchFn) { fetchFn = newFetchFn; } const result$ = iterateAsync(onFetchHooks, onFetch => onFetch({ fetchFn, setFetchFn, url, setURL(newUrl) { url = String(newUrl); }, options, setOptions(newOptions) { options = newOptions; }, context, info, }), doneHooks); function handleIterationResult() { const response$ = fetchFn(url, options, context, info); if (doneHooks.length === 0) { return response$; } if (isPromise(response$)) { return response$.then(response => handleOnFetchDone(response, doneHooks)); } return handleOnFetchDone(response$, doneHooks); } if (isPromise(result$)) { return result$.then(handleIterationResult); } return handleIterationResult(); }; } function handleOnFetchDone(response, onFetchDoneHooks) { function setResponse(newResponse) { response = newResponse; } const result$ = iterateAsync(onFetchDoneHooks, onFetchDone => onFetchDone({ response, setResponse, })); if (isPromise(result$)) { return result$.then(() => response); } return response; }