UNPKG

@graphql-yoga/urql-exchange

Version:
91 lines (90 loc) 4.03 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.yogaExchange = void 0; const wonka_1 = require("wonka"); const core_1 = require("@urql/core"); const utils_1 = require("@graphql-tools/utils"); const url_loader_1 = require("@graphql-tools/url-loader"); function yogaExchange(options) { const urlLoader = new url_loader_1.UrlLoader(); // eslint-disable-next-line @typescript-eslint/no-explicit-any function makeYogaSource(operation) { const operationName = (0, core_1.getOperationName)(operation.query); // eslint-disable-next-line @typescript-eslint/no-explicit-any const executionRequest = { document: operation.query, operationName, operationType: operation.kind, variables: operation.variables, context: operation.context, extensions: { endpoint: operation.context.url, headers: operation.context.headers, }, }; const extraFetchOptions = typeof operation.context.fetchOptions === 'function' ? operation.context.fetchOptions() : operation.context.fetchOptions; const executor = urlLoader.getExecutorAsync(options?.endpoint || operation.context.url, { subscriptionsProtocol: url_loader_1.SubscriptionProtocol.SSE, multipart: true, customFetch: operation.context.fetch, useGETForQueries: !!operation.context.preferGetMethod, headers: extraFetchOptions?.headers, method: extraFetchOptions?.method, credentials: extraFetchOptions?.credentials, ...options, }); return (0, wonka_1.make)((observer) => { let ended = false; executor(executionRequest) .then(async (result) => { if (ended || !result) { return; } if (!(0, utils_1.isAsyncIterable)(result)) { observer.next((0, core_1.makeResult)(operation, result)); } else { let prevResult = null; for await (const value of result) { if (value) { prevResult = prevResult ? (0, core_1.mergeResultPatch)(prevResult, value) : (0, core_1.makeResult)(operation, value); observer.next(prevResult); } if (ended) { break; } } } observer.complete(); }) .catch((error) => { observer.next((0, core_1.makeErrorResult)(operation, error)); }) .finally(() => { ended = true; observer.complete(); }); return () => { ended = true; }; }); } return function yogaExchangeFn({ forward }) { return function yogaExchangeIO(ops$) { const sharedOps$ = (0, wonka_1.share)(ops$); const executedOps$ = (0, wonka_1.pipe)(sharedOps$, (0, wonka_1.filter)((operation) => operation.kind === 'query' || operation.kind === 'mutation' || operation.kind === 'subscription'), (0, wonka_1.mergeMap)((operation) => { const teardown$ = (0, wonka_1.pipe)(sharedOps$, (0, wonka_1.filter)((op) => op.kind === 'teardown' && op.key === operation.key)); return (0, wonka_1.pipe)(makeYogaSource(operation), (0, wonka_1.takeUntil)(teardown$)); })); const forwardedOps$ = (0, wonka_1.pipe)(sharedOps$, (0, wonka_1.filter)((operation) => operation.kind === 'teardown'), forward); return (0, wonka_1.merge)([executedOps$, forwardedOps$]); }; }; } exports.yogaExchange = yogaExchange;