@graphql-yoga/apollo-link
Version:
50 lines (49 loc) • 1.82 kB
JavaScript
import * as apolloImport from '@apollo/client';
import { SubscriptionProtocol, UrlLoader, } from '@graphql-tools/url-loader';
import { isAsyncIterable } from '@graphql-tools/utils';
const apollo = apolloImport?.default ?? apolloImport;
function createYogaApolloRequestHandler(options) {
const urlLoader = new UrlLoader();
const executor = urlLoader.getExecutorAsync(options.endpoint, {
subscriptionsProtocol: SubscriptionProtocol.SSE,
multipart: true,
...options,
});
return function graphQLYogaApolloRequestHandler(operation) {
return new apollo.Observable((observer) => {
const executionRequest = {
document: operation.query,
variables: operation.variables,
operationName: operation.operationName,
extensions: operation.extensions,
context: operation.getContext(),
};
executor(executionRequest)
.then(async (results) => {
if (isAsyncIterable(results)) {
for await (const result of results) {
if (observer.closed) {
return;
}
observer.next(result);
}
observer.complete();
}
else if (!observer.closed) {
observer.next(results);
observer.complete();
}
})
.catch((error) => {
if (!observer.closed) {
observer.error(error);
}
});
});
};
}
export class YogaLink extends apollo.ApolloLink {
constructor(options) {
super(createYogaApolloRequestHandler(options));
}
}