@graphql-tools/links
Version:
A set of utils for faster development of GraphQL tools
46 lines (45 loc) • 1.81 kB
JavaScript
var _a;
import * as apolloImport from '@apollo/client';
const apollo = (_a = apolloImport === null || apolloImport === void 0 ? void 0 : apolloImport.default) !== null && _a !== void 0 ? _a : apolloImport;
function getFinalPromise(object) {
return Promise.resolve(object).then(resolvedObject => {
if (resolvedObject == null) {
return resolvedObject;
}
if (Array.isArray(resolvedObject)) {
return Promise.all(resolvedObject.map(o => getFinalPromise(o)));
}
else if (typeof resolvedObject === 'object') {
const keys = Object.keys(resolvedObject);
return Promise.all(keys.map(key => getFinalPromise(resolvedObject[key]))).then(awaitedValues => {
for (let i = 0; i < keys.length; i++) {
resolvedObject[keys[i]] = awaitedValues[i];
}
return resolvedObject;
});
}
return resolvedObject;
});
}
export class AwaitVariablesLink extends apollo.ApolloLink {
request(operation, forward) {
return new apollo.Observable(observer => {
let subscription;
getFinalPromise(operation.variables)
.then(resolvedVariables => {
operation.variables = resolvedVariables;
subscription = forward(operation).subscribe({
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
});
})
.catch(observer.error.bind(observer));
return () => {
if (subscription != null) {
subscription.unsubscribe();
}
};
});
}
}