@graphql-tools/executor-urql-exchange
Version:
76 lines (75 loc) • 3.52 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.executorExchange = void 0;
const wonka_1 = require("wonka");
const core_1 = require("@urql/core");
const utils_1 = require("@graphql-tools/utils");
function executorExchange(executor) {
function makeYogaSource(operation) {
const operationName = (0, core_1.getOperationName)(operation.query);
const extraFetchOptions = typeof operation.context.fetchOptions === 'function'
? operation.context.fetchOptions()
: operation.context.fetchOptions;
const executionRequest = {
document: operation.query,
operationName,
operationType: operation.kind,
variables: operation.variables,
context: operation.context,
extensions: {
endpoint: operation.context.url,
fetch: operation.context.fetch,
useGETForQueries: operation.context.preferGetMethod,
headers: extraFetchOptions === null || extraFetchOptions === void 0 ? void 0 : extraFetchOptions.headers,
method: extraFetchOptions === null || extraFetchOptions === void 0 ? void 0 : extraFetchOptions.method,
},
};
return (0, wonka_1.make)(observer => {
let ended = false;
Promise.resolve(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 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$]);
};
};
}
exports.executorExchange = executorExchange;
;