UNPKG

@graphql-mesh/utils

Version:
90 lines (89 loc) 3.77 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.loggerForExecutionRequest = exports.requestIdByRequest = void 0; exports.wrapFetchWithHooks = wrapFetchWithHooks; const instrumentation_1 = require("@envelop/instrumentation"); const promise_helpers_1 = require("@whatwg-node/promise-helpers"); const logger_js_1 = require("./logger.js"); exports.requestIdByRequest = new WeakMap(); exports.loggerForExecutionRequest = new WeakMap(); function wrapFetchWithHooks(onFetchHooks, instrumentation, defaultLogger) { let wrappedFetchFn = function wrappedFetchFn(url, options, context, info) { let fetchFn; let response$; const onFetchDoneHooks = []; return (0, promise_helpers_1.handleMaybePromise)(() => (0, promise_helpers_1.iterateAsync)(onFetchHooks, (onFetch, endEarly) => onFetch({ fetchFn, setFetchFn(newFetchFn) { fetchFn = newFetchFn; }, url, setURL(newUrl) { url = String(newUrl); }, options, setOptions(newOptions) { options = newOptions; }, context, info, get executionRequest() { return info?.executionRequest; }, get requestId() { if (context?.request) { return exports.requestIdByRequest.get(context.request); } }, get logger() { let logger; if (info?.executionRequest) { logger = exports.loggerForExecutionRequest.get(info.executionRequest); } if (!logger) { logger = defaultLogger?.child('fetch') || new logger_js_1.DefaultLogger('fetch'); } if (context?.request) { const requestId = exports.requestIdByRequest.get(context.request); if (requestId) { logger = logger.child({ requestId }); } } if (info?.executionRequest) { exports.loggerForExecutionRequest.set(info.executionRequest, logger); } return logger; }, endResponse(newResponse) { response$ = newResponse; endEarly(); }, }), onFetchDoneHooks), function handleIterationResult() { return (0, promise_helpers_1.handleMaybePromise)(() => response$ || fetchFn(url, options, context, info), function (response) { return (0, promise_helpers_1.handleMaybePromise)(() => (0, promise_helpers_1.iterateAsync)(onFetchDoneHooks, onFetchDone => onFetchDone({ response, setResponse(newResponse) { response = newResponse; }, })), function handleOnFetchDone() { return response; }); }); }); }; if (instrumentation) { const originalWrappedFetch = wrappedFetchFn; wrappedFetchFn = function wrappedFetchFn(url, options, context, info) { const fetchInstrument = instrumentation()?.fetch; const instrumentedFetch = fetchInstrument ? (0, instrumentation_1.getInstrumented)({ get executionRequest() { return info?.executionRequest; }, }).asyncFn(fetchInstrument, originalWrappedFetch) : originalWrappedFetch; return instrumentedFetch(url, options, context, info); }; } return wrappedFetchFn; }