@graphql-tools/executor-urql-exchange
Version:
87 lines (86 loc) • 4 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.executorExchange = executorExchange;
const wonka_1 = require("wonka");
const utils_1 = require("@graphql-tools/utils");
const core_1 = require("@urql/core");
const promise_helpers_1 = require("@whatwg-node/promise-helpers");
function executorExchange(executor) {
function makeYogaSource(operation) {
const extraFetchOptions = typeof operation.context.fetchOptions === 'function'
? operation.context.fetchOptions()
: operation.context.fetchOptions;
const executionRequest = {
document: operation.query,
operationType: operation.kind,
variables: operation.variables,
context: operation.context,
extensions: {
endpoint: operation.context.url,
fetch: operation.context.fetch,
useGETForQueries: operation.context.preferGetMethod,
headers: extraFetchOptions?.headers,
method: extraFetchOptions?.method,
},
};
return (0, wonka_1.make)(observer => {
let ended = false;
let iterator;
(0, promise_helpers_1.handleMaybePromise)(() => executor(executionRequest), result => {
if (ended || !result) {
return;
}
if (!(0, utils_1.isAsyncIterable)(result)) {
observer.next((0, core_1.makeResult)(operation, result));
observer.complete();
}
else {
let prevResult = null;
iterator = result[Symbol.asyncIterator]();
function iterate() {
if (ended) {
return;
}
return iterator.next().then(({ value, done }) => {
if (done) {
return;
}
if (value) {
if (prevResult && value.incremental) {
prevResult = (0, core_1.mergeResultPatch)(prevResult, value);
}
else {
prevResult = (0, core_1.makeResult)(operation, value);
}
observer.next(prevResult);
}
return iterate();
});
}
return (0, promise_helpers_1.handleMaybePromise)(() => iterate(), () => observer.complete());
}
}, error => {
observer.next((0, core_1.makeErrorResult)(operation, error));
ended = true;
observer.complete();
});
return () => {
iterator?.return?.();
ended = true;
};
});
}
return function executorExchangeFn({ forward }) {
return function executorExchangeIO(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$]);
};
};
}
;