apollo-client
Version:
A simple yet functional GraphQL client.
1,052 lines (1,040 loc) • 101 kB
JavaScript
import { __extends, __assign, __awaiter, __generator } from 'tslib';
import { getOperationDefinition, isEqual, tryFunctionOrLogError, cloneDeep, mergeDeep, hasDirectives, removeClientSetsFromDocument, buildQueryFromSelectionSet, getMainDefinition, getFragmentDefinitions, createFragmentMap, mergeDeepArray, resultKeyNameFromField, argumentsObjectFromField, shouldInclude, isField, isInlineFragment, canUseWeakMap, graphQLResultHasError, removeConnectionDirectiveFromDocument, hasClientExports, getDefaultValues, getOperationName } from 'apollo-utilities';
import { Observable as Observable$1, execute, ApolloLink } from 'apollo-link';
import $$observable from 'symbol-observable';
import { InvariantError, invariant } from 'ts-invariant';
import { visit, BREAK } from 'graphql/language/visitor';
var NetworkStatus;
(function (NetworkStatus) {
NetworkStatus[NetworkStatus["loading"] = 1] = "loading";
NetworkStatus[NetworkStatus["setVariables"] = 2] = "setVariables";
NetworkStatus[NetworkStatus["fetchMore"] = 3] = "fetchMore";
NetworkStatus[NetworkStatus["refetch"] = 4] = "refetch";
NetworkStatus[NetworkStatus["poll"] = 6] = "poll";
NetworkStatus[NetworkStatus["ready"] = 7] = "ready";
NetworkStatus[NetworkStatus["error"] = 8] = "error";
})(NetworkStatus || (NetworkStatus = {}));
function isNetworkRequestInFlight(networkStatus) {
return networkStatus < 7;
}
var Observable = (function (_super) {
__extends(Observable, _super);
function Observable() {
return _super !== null && _super.apply(this, arguments) || this;
}
Observable.prototype[$$observable] = function () {
return this;
};
Observable.prototype['@@observable'] = function () {
return this;
};
return Observable;
}(Observable$1));
function isNonEmptyArray(value) {
return Array.isArray(value) && value.length > 0;
}
function isApolloError(err) {
return err.hasOwnProperty('graphQLErrors');
}
var generateErrorMessage = function (err) {
var message = '';
if (isNonEmptyArray(err.graphQLErrors)) {
err.graphQLErrors.forEach(function (graphQLError) {
var errorMessage = graphQLError
? graphQLError.message
: 'Error message not found.';
message += "GraphQL error: " + errorMessage + "\n";
});
}
if (err.networkError) {
message += 'Network error: ' + err.networkError.message + '\n';
}
message = message.replace(/\n$/, '');
return message;
};
var ApolloError = (function (_super) {
__extends(ApolloError, _super);
function ApolloError(_a) {
var graphQLErrors = _a.graphQLErrors, networkError = _a.networkError, errorMessage = _a.errorMessage, extraInfo = _a.extraInfo;
var _this = _super.call(this, errorMessage) || this;
_this.graphQLErrors = graphQLErrors || [];
_this.networkError = networkError || null;
if (!errorMessage) {
_this.message = generateErrorMessage(_this);
}
else {
_this.message = errorMessage;
}
_this.extraInfo = extraInfo;
_this.__proto__ = ApolloError.prototype;
return _this;
}
return ApolloError;
}(Error));
var FetchType;
(function (FetchType) {
FetchType[FetchType["normal"] = 1] = "normal";
FetchType[FetchType["refetch"] = 2] = "refetch";
FetchType[FetchType["poll"] = 3] = "poll";
})(FetchType || (FetchType = {}));
var hasError = function (storeValue, policy) {
if (policy === void 0) { policy = 'none'; }
return storeValue && (storeValue.networkError ||
(policy === 'none' && isNonEmptyArray(storeValue.graphQLErrors)));
};
var ObservableQuery = (function (_super) {
__extends(ObservableQuery, _super);
function ObservableQuery(_a) {
var queryManager = _a.queryManager, options = _a.options, _b = _a.shouldSubscribe, shouldSubscribe = _b === void 0 ? true : _b;
var _this = _super.call(this, function (observer) {
return _this.onSubscribe(observer);
}) || this;
_this.observers = new Set();
_this.subscriptions = new Set();
_this.isTornDown = false;
_this.options = options;
_this.variables = options.variables || {};
_this.queryId = queryManager.generateQueryId();
_this.shouldSubscribe = shouldSubscribe;
var opDef = getOperationDefinition(options.query);
_this.queryName = opDef && opDef.name && opDef.name.value;
_this.queryManager = queryManager;
return _this;
}
ObservableQuery.prototype.result = function () {
var _this = this;
return new Promise(function (resolve, reject) {
var observer = {
next: function (result) {
resolve(result);
_this.observers.delete(observer);
if (!_this.observers.size) {
_this.queryManager.removeQuery(_this.queryId);
}
setTimeout(function () {
subscription.unsubscribe();
}, 0);
},
error: reject,
};
var subscription = _this.subscribe(observer);
});
};
ObservableQuery.prototype.currentResult = function () {
var result = this.getCurrentResult();
if (result.data === undefined) {
result.data = {};
}
return result;
};
ObservableQuery.prototype.getCurrentResult = function () {
if (this.isTornDown) {
var lastResult = this.lastResult;
return {
data: !this.lastError && lastResult && lastResult.data || void 0,
error: this.lastError,
loading: false,
networkStatus: NetworkStatus.error,
};
}
var _a = this.queryManager.getCurrentQueryResult(this), data = _a.data, partial = _a.partial;
var queryStoreValue = this.queryManager.queryStore.get(this.queryId);
var result;
var fetchPolicy = this.options.fetchPolicy;
var isNetworkFetchPolicy = fetchPolicy === 'network-only' ||
fetchPolicy === 'no-cache';
if (queryStoreValue) {
var networkStatus = queryStoreValue.networkStatus;
if (hasError(queryStoreValue, this.options.errorPolicy)) {
return {
data: void 0,
loading: false,
networkStatus: networkStatus,
error: new ApolloError({
graphQLErrors: queryStoreValue.graphQLErrors,
networkError: queryStoreValue.networkError,
}),
};
}
if (queryStoreValue.variables) {
this.options.variables = __assign(__assign({}, this.options.variables), queryStoreValue.variables);
this.variables = this.options.variables;
}
result = {
data: data,
loading: isNetworkRequestInFlight(networkStatus),
networkStatus: networkStatus,
};
if (queryStoreValue.graphQLErrors && this.options.errorPolicy === 'all') {
result.errors = queryStoreValue.graphQLErrors;
}
}
else {
var loading = isNetworkFetchPolicy ||
(partial && fetchPolicy !== 'cache-only');
result = {
data: data,
loading: loading,
networkStatus: loading ? NetworkStatus.loading : NetworkStatus.ready,
};
}
if (!partial) {
this.updateLastResult(__assign(__assign({}, result), { stale: false }));
}
return __assign(__assign({}, result), { partial: partial });
};
ObservableQuery.prototype.isDifferentFromLastResult = function (newResult) {
var snapshot = this.lastResultSnapshot;
return !(snapshot &&
newResult &&
snapshot.networkStatus === newResult.networkStatus &&
snapshot.stale === newResult.stale &&
isEqual(snapshot.data, newResult.data));
};
ObservableQuery.prototype.getLastResult = function () {
return this.lastResult;
};
ObservableQuery.prototype.getLastError = function () {
return this.lastError;
};
ObservableQuery.prototype.resetLastResults = function () {
delete this.lastResult;
delete this.lastResultSnapshot;
delete this.lastError;
this.isTornDown = false;
};
ObservableQuery.prototype.resetQueryStoreErrors = function () {
var queryStore = this.queryManager.queryStore.get(this.queryId);
if (queryStore) {
queryStore.networkError = null;
queryStore.graphQLErrors = [];
}
};
ObservableQuery.prototype.refetch = function (variables) {
var fetchPolicy = this.options.fetchPolicy;
if (fetchPolicy === 'cache-only') {
return Promise.reject(process.env.NODE_ENV === "production" ? new InvariantError(1) : new InvariantError('cache-only fetchPolicy option should not be used together with query refetch.'));
}
if (fetchPolicy !== 'no-cache' &&
fetchPolicy !== 'cache-and-network') {
fetchPolicy = 'network-only';
}
if (!isEqual(this.variables, variables)) {
this.variables = __assign(__assign({}, this.variables), variables);
}
if (!isEqual(this.options.variables, this.variables)) {
this.options.variables = __assign(__assign({}, this.options.variables), this.variables);
}
return this.queryManager.fetchQuery(this.queryId, __assign(__assign({}, this.options), { fetchPolicy: fetchPolicy }), FetchType.refetch);
};
ObservableQuery.prototype.fetchMore = function (fetchMoreOptions) {
var _this = this;
process.env.NODE_ENV === "production" ? invariant(fetchMoreOptions.updateQuery, 2) : invariant(fetchMoreOptions.updateQuery, 'updateQuery option is required. This function defines how to update the query data with the new results.');
var combinedOptions = __assign(__assign({}, (fetchMoreOptions.query ? fetchMoreOptions : __assign(__assign(__assign({}, this.options), fetchMoreOptions), { variables: __assign(__assign({}, this.variables), fetchMoreOptions.variables) }))), { fetchPolicy: 'network-only' });
var qid = this.queryManager.generateQueryId();
return this.queryManager
.fetchQuery(qid, combinedOptions, FetchType.normal, this.queryId)
.then(function (fetchMoreResult) {
_this.updateQuery(function (previousResult) {
return fetchMoreOptions.updateQuery(previousResult, {
fetchMoreResult: fetchMoreResult.data,
variables: combinedOptions.variables,
});
});
_this.queryManager.stopQuery(qid);
return fetchMoreResult;
}, function (error) {
_this.queryManager.stopQuery(qid);
throw error;
});
};
ObservableQuery.prototype.subscribeToMore = function (options) {
var _this = this;
var subscription = this.queryManager
.startGraphQLSubscription({
query: options.document,
variables: options.variables,
})
.subscribe({
next: function (subscriptionData) {
var updateQuery = options.updateQuery;
if (updateQuery) {
_this.updateQuery(function (previous, _a) {
var variables = _a.variables;
return updateQuery(previous, {
subscriptionData: subscriptionData,
variables: variables,
});
});
}
},
error: function (err) {
if (options.onError) {
options.onError(err);
return;
}
process.env.NODE_ENV === "production" || invariant.error('Unhandled GraphQL subscription error', err);
},
});
this.subscriptions.add(subscription);
return function () {
if (_this.subscriptions.delete(subscription)) {
subscription.unsubscribe();
}
};
};
ObservableQuery.prototype.setOptions = function (opts) {
var oldFetchPolicy = this.options.fetchPolicy;
this.options = __assign(__assign({}, this.options), opts);
if (opts.pollInterval) {
this.startPolling(opts.pollInterval);
}
else if (opts.pollInterval === 0) {
this.stopPolling();
}
var fetchPolicy = opts.fetchPolicy;
return this.setVariables(this.options.variables, oldFetchPolicy !== fetchPolicy && (oldFetchPolicy === 'cache-only' ||
oldFetchPolicy === 'standby' ||
fetchPolicy === 'network-only'), opts.fetchResults);
};
ObservableQuery.prototype.setVariables = function (variables, tryFetch, fetchResults) {
if (tryFetch === void 0) { tryFetch = false; }
if (fetchResults === void 0) { fetchResults = true; }
this.isTornDown = false;
variables = variables || this.variables;
if (!tryFetch && isEqual(variables, this.variables)) {
return this.observers.size && fetchResults
? this.result()
: Promise.resolve();
}
this.variables = this.options.variables = variables;
if (!this.observers.size) {
return Promise.resolve();
}
return this.queryManager.fetchQuery(this.queryId, this.options);
};
ObservableQuery.prototype.updateQuery = function (mapFn) {
var queryManager = this.queryManager;
var _a = queryManager.getQueryWithPreviousResult(this.queryId), previousResult = _a.previousResult, variables = _a.variables, document = _a.document;
var newResult = tryFunctionOrLogError(function () {
return mapFn(previousResult, { variables: variables });
});
if (newResult) {
queryManager.dataStore.markUpdateQueryResult(document, variables, newResult);
queryManager.broadcastQueries();
}
};
ObservableQuery.prototype.stopPolling = function () {
this.queryManager.stopPollingQuery(this.queryId);
this.options.pollInterval = undefined;
};
ObservableQuery.prototype.startPolling = function (pollInterval) {
assertNotCacheFirstOrOnly(this);
this.options.pollInterval = pollInterval;
this.queryManager.startPollingQuery(this.options, this.queryId);
};
ObservableQuery.prototype.updateLastResult = function (newResult) {
var previousResult = this.lastResult;
this.lastResult = newResult;
this.lastResultSnapshot = this.queryManager.assumeImmutableResults
? newResult
: cloneDeep(newResult);
return previousResult;
};
ObservableQuery.prototype.onSubscribe = function (observer) {
var _this = this;
try {
var subObserver = observer._subscription._observer;
if (subObserver && !subObserver.error) {
subObserver.error = defaultSubscriptionObserverErrorCallback;
}
}
catch (_a) { }
var first = !this.observers.size;
this.observers.add(observer);
if (observer.next && this.lastResult)
observer.next(this.lastResult);
if (observer.error && this.lastError)
observer.error(this.lastError);
if (first) {
this.setUpQuery();
}
return function () {
if (_this.observers.delete(observer) && !_this.observers.size) {
_this.tearDownQuery();
}
};
};
ObservableQuery.prototype.setUpQuery = function () {
var _this = this;
var _a = this, queryManager = _a.queryManager, queryId = _a.queryId;
if (this.shouldSubscribe) {
queryManager.addObservableQuery(queryId, this);
}
if (this.options.pollInterval) {
assertNotCacheFirstOrOnly(this);
queryManager.startPollingQuery(this.options, queryId);
}
var onError = function (error) {
_this.updateLastResult(__assign(__assign({}, _this.lastResult), { errors: error.graphQLErrors, networkStatus: NetworkStatus.error, loading: false }));
iterateObserversSafely(_this.observers, 'error', _this.lastError = error);
};
queryManager.observeQuery(queryId, this.options, {
next: function (result) {
if (_this.lastError || _this.isDifferentFromLastResult(result)) {
var previousResult_1 = _this.updateLastResult(result);
var _a = _this.options, query_1 = _a.query, variables = _a.variables, fetchPolicy_1 = _a.fetchPolicy;
if (queryManager.transform(query_1).hasClientExports) {
queryManager.getLocalState().addExportedVariables(query_1, variables).then(function (variables) {
var previousVariables = _this.variables;
_this.variables = _this.options.variables = variables;
if (!result.loading &&
previousResult_1 &&
fetchPolicy_1 !== 'cache-only' &&
queryManager.transform(query_1).serverQuery &&
!isEqual(previousVariables, variables)) {
_this.refetch();
}
else {
iterateObserversSafely(_this.observers, 'next', result);
}
});
}
else {
iterateObserversSafely(_this.observers, 'next', result);
}
}
},
error: onError,
}).catch(onError);
};
ObservableQuery.prototype.tearDownQuery = function () {
var queryManager = this.queryManager;
this.isTornDown = true;
queryManager.stopPollingQuery(this.queryId);
this.subscriptions.forEach(function (sub) { return sub.unsubscribe(); });
this.subscriptions.clear();
queryManager.removeObservableQuery(this.queryId);
queryManager.stopQuery(this.queryId);
this.observers.clear();
};
return ObservableQuery;
}(Observable));
function defaultSubscriptionObserverErrorCallback(error) {
process.env.NODE_ENV === "production" || invariant.error('Unhandled error', error.message, error.stack);
}
function iterateObserversSafely(observers, method, argument) {
var observersWithMethod = [];
observers.forEach(function (obs) { return obs[method] && observersWithMethod.push(obs); });
observersWithMethod.forEach(function (obs) { return obs[method](argument); });
}
function assertNotCacheFirstOrOnly(obsQuery) {
var fetchPolicy = obsQuery.options.fetchPolicy;
process.env.NODE_ENV === "production" ? invariant(fetchPolicy !== 'cache-first' && fetchPolicy !== 'cache-only', 3) : invariant(fetchPolicy !== 'cache-first' && fetchPolicy !== 'cache-only', 'Queries that specify the cache-first and cache-only fetchPolicies cannot also be polling queries.');
}
var MutationStore = (function () {
function MutationStore() {
this.store = {};
}
MutationStore.prototype.getStore = function () {
return this.store;
};
MutationStore.prototype.get = function (mutationId) {
return this.store[mutationId];
};
MutationStore.prototype.initMutation = function (mutationId, mutation, variables) {
this.store[mutationId] = {
mutation: mutation,
variables: variables || {},
loading: true,
error: null,
};
};
MutationStore.prototype.markMutationError = function (mutationId, error) {
var mutation = this.store[mutationId];
if (mutation) {
mutation.loading = false;
mutation.error = error;
}
};
MutationStore.prototype.markMutationResult = function (mutationId) {
var mutation = this.store[mutationId];
if (mutation) {
mutation.loading = false;
mutation.error = null;
}
};
MutationStore.prototype.reset = function () {
this.store = {};
};
return MutationStore;
}());
var QueryStore = (function () {
function QueryStore() {
this.store = {};
}
QueryStore.prototype.getStore = function () {
return this.store;
};
QueryStore.prototype.get = function (queryId) {
return this.store[queryId];
};
QueryStore.prototype.initQuery = function (query) {
var previousQuery = this.store[query.queryId];
process.env.NODE_ENV === "production" ? invariant(!previousQuery ||
previousQuery.document === query.document ||
isEqual(previousQuery.document, query.document), 19) : invariant(!previousQuery ||
previousQuery.document === query.document ||
isEqual(previousQuery.document, query.document), 'Internal Error: may not update existing query string in store');
var isSetVariables = false;
var previousVariables = null;
if (query.storePreviousVariables &&
previousQuery &&
previousQuery.networkStatus !== NetworkStatus.loading) {
if (!isEqual(previousQuery.variables, query.variables)) {
isSetVariables = true;
previousVariables = previousQuery.variables;
}
}
var networkStatus;
if (isSetVariables) {
networkStatus = NetworkStatus.setVariables;
}
else if (query.isPoll) {
networkStatus = NetworkStatus.poll;
}
else if (query.isRefetch) {
networkStatus = NetworkStatus.refetch;
}
else {
networkStatus = NetworkStatus.loading;
}
var graphQLErrors = [];
if (previousQuery && previousQuery.graphQLErrors) {
graphQLErrors = previousQuery.graphQLErrors;
}
this.store[query.queryId] = {
document: query.document,
variables: query.variables,
previousVariables: previousVariables,
networkError: null,
graphQLErrors: graphQLErrors,
networkStatus: networkStatus,
metadata: query.metadata,
};
if (typeof query.fetchMoreForQueryId === 'string' &&
this.store[query.fetchMoreForQueryId]) {
this.store[query.fetchMoreForQueryId].networkStatus =
NetworkStatus.fetchMore;
}
};
QueryStore.prototype.markQueryResult = function (queryId, result, fetchMoreForQueryId) {
if (!this.store || !this.store[queryId])
return;
this.store[queryId].networkError = null;
this.store[queryId].graphQLErrors = isNonEmptyArray(result.errors) ? result.errors : [];
this.store[queryId].previousVariables = null;
this.store[queryId].networkStatus = NetworkStatus.ready;
if (typeof fetchMoreForQueryId === 'string' &&
this.store[fetchMoreForQueryId]) {
this.store[fetchMoreForQueryId].networkStatus = NetworkStatus.ready;
}
};
QueryStore.prototype.markQueryError = function (queryId, error, fetchMoreForQueryId) {
if (!this.store || !this.store[queryId])
return;
this.store[queryId].networkError = error;
this.store[queryId].networkStatus = NetworkStatus.error;
if (typeof fetchMoreForQueryId === 'string') {
this.markQueryResultClient(fetchMoreForQueryId, true);
}
};
QueryStore.prototype.markQueryResultClient = function (queryId, complete) {
var storeValue = this.store && this.store[queryId];
if (storeValue) {
storeValue.networkError = null;
storeValue.previousVariables = null;
if (complete) {
storeValue.networkStatus = NetworkStatus.ready;
}
}
};
QueryStore.prototype.stopQuery = function (queryId) {
delete this.store[queryId];
};
QueryStore.prototype.reset = function (observableQueryIds) {
var _this = this;
Object.keys(this.store).forEach(function (queryId) {
if (observableQueryIds.indexOf(queryId) < 0) {
_this.stopQuery(queryId);
}
else {
_this.store[queryId].networkStatus = NetworkStatus.loading;
}
});
};
return QueryStore;
}());
function capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
var LocalState = (function () {
function LocalState(_a) {
var cache = _a.cache, client = _a.client, resolvers = _a.resolvers, fragmentMatcher = _a.fragmentMatcher;
this.cache = cache;
if (client) {
this.client = client;
}
if (resolvers) {
this.addResolvers(resolvers);
}
if (fragmentMatcher) {
this.setFragmentMatcher(fragmentMatcher);
}
}
LocalState.prototype.addResolvers = function (resolvers) {
var _this = this;
this.resolvers = this.resolvers || {};
if (Array.isArray(resolvers)) {
resolvers.forEach(function (resolverGroup) {
_this.resolvers = mergeDeep(_this.resolvers, resolverGroup);
});
}
else {
this.resolvers = mergeDeep(this.resolvers, resolvers);
}
};
LocalState.prototype.setResolvers = function (resolvers) {
this.resolvers = {};
this.addResolvers(resolvers);
};
LocalState.prototype.getResolvers = function () {
return this.resolvers || {};
};
LocalState.prototype.runResolvers = function (_a) {
var document = _a.document, remoteResult = _a.remoteResult, context = _a.context, variables = _a.variables, _b = _a.onlyRunForcedResolvers, onlyRunForcedResolvers = _b === void 0 ? false : _b;
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_c) {
if (document) {
return [2, this.resolveDocument(document, remoteResult.data, context, variables, this.fragmentMatcher, onlyRunForcedResolvers).then(function (localResult) { return (__assign(__assign({}, remoteResult), { data: localResult.result })); })];
}
return [2, remoteResult];
});
});
};
LocalState.prototype.setFragmentMatcher = function (fragmentMatcher) {
this.fragmentMatcher = fragmentMatcher;
};
LocalState.prototype.getFragmentMatcher = function () {
return this.fragmentMatcher;
};
LocalState.prototype.clientQuery = function (document) {
if (hasDirectives(['client'], document)) {
if (this.resolvers) {
return document;
}
process.env.NODE_ENV === "production" || invariant.warn('Found @client directives in a query but no ApolloClient resolvers ' +
'were specified. This means ApolloClient local resolver handling ' +
'has been disabled, and @client directives will be passed through ' +
'to your link chain.');
}
return null;
};
LocalState.prototype.serverQuery = function (document) {
return this.resolvers ? removeClientSetsFromDocument(document) : document;
};
LocalState.prototype.prepareContext = function (context) {
if (context === void 0) { context = {}; }
var cache = this.cache;
var newContext = __assign(__assign({}, context), { cache: cache, getCacheKey: function (obj) {
if (cache.config) {
return cache.config.dataIdFromObject(obj);
}
else {
process.env.NODE_ENV === "production" ? invariant(false, 6) : invariant(false, 'To use context.getCacheKey, you need to use a cache that has ' +
'a configurable dataIdFromObject, like apollo-cache-inmemory.');
}
} });
return newContext;
};
LocalState.prototype.addExportedVariables = function (document, variables, context) {
if (variables === void 0) { variables = {}; }
if (context === void 0) { context = {}; }
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
if (document) {
return [2, this.resolveDocument(document, this.buildRootValueFromCache(document, variables) || {}, this.prepareContext(context), variables).then(function (data) { return (__assign(__assign({}, variables), data.exportedVariables)); })];
}
return [2, __assign({}, variables)];
});
});
};
LocalState.prototype.shouldForceResolvers = function (document) {
var forceResolvers = false;
visit(document, {
Directive: {
enter: function (node) {
if (node.name.value === 'client' && node.arguments) {
forceResolvers = node.arguments.some(function (arg) {
return arg.name.value === 'always' &&
arg.value.kind === 'BooleanValue' &&
arg.value.value === true;
});
if (forceResolvers) {
return BREAK;
}
}
},
},
});
return forceResolvers;
};
LocalState.prototype.buildRootValueFromCache = function (document, variables) {
return this.cache.diff({
query: buildQueryFromSelectionSet(document),
variables: variables,
returnPartialData: true,
optimistic: false,
}).result;
};
LocalState.prototype.resolveDocument = function (document, rootValue, context, variables, fragmentMatcher, onlyRunForcedResolvers) {
if (context === void 0) { context = {}; }
if (variables === void 0) { variables = {}; }
if (fragmentMatcher === void 0) { fragmentMatcher = function () { return true; }; }
if (onlyRunForcedResolvers === void 0) { onlyRunForcedResolvers = false; }
return __awaiter(this, void 0, void 0, function () {
var mainDefinition, fragments, fragmentMap, definitionOperation, defaultOperationType, _a, cache, client, execContext;
return __generator(this, function (_b) {
mainDefinition = getMainDefinition(document);
fragments = getFragmentDefinitions(document);
fragmentMap = createFragmentMap(fragments);
definitionOperation = mainDefinition
.operation;
defaultOperationType = definitionOperation
? capitalizeFirstLetter(definitionOperation)
: 'Query';
_a = this, cache = _a.cache, client = _a.client;
execContext = {
fragmentMap: fragmentMap,
context: __assign(__assign({}, context), { cache: cache,
client: client }),
variables: variables,
fragmentMatcher: fragmentMatcher,
defaultOperationType: defaultOperationType,
exportedVariables: {},
onlyRunForcedResolvers: onlyRunForcedResolvers,
};
return [2, this.resolveSelectionSet(mainDefinition.selectionSet, rootValue, execContext).then(function (result) { return ({
result: result,
exportedVariables: execContext.exportedVariables,
}); })];
});
});
};
LocalState.prototype.resolveSelectionSet = function (selectionSet, rootValue, execContext) {
return __awaiter(this, void 0, void 0, function () {
var fragmentMap, context, variables, resultsToMerge, execute;
var _this = this;
return __generator(this, function (_a) {
fragmentMap = execContext.fragmentMap, context = execContext.context, variables = execContext.variables;
resultsToMerge = [rootValue];
execute = function (selection) { return __awaiter(_this, void 0, void 0, function () {
var fragment, typeCondition;
return __generator(this, function (_a) {
if (!shouldInclude(selection, variables)) {
return [2];
}
if (isField(selection)) {
return [2, this.resolveField(selection, rootValue, execContext).then(function (fieldResult) {
var _a;
if (typeof fieldResult !== 'undefined') {
resultsToMerge.push((_a = {},
_a[resultKeyNameFromField(selection)] = fieldResult,
_a));
}
})];
}
if (isInlineFragment(selection)) {
fragment = selection;
}
else {
fragment = fragmentMap[selection.name.value];
process.env.NODE_ENV === "production" ? invariant(fragment, 7) : invariant(fragment, "No fragment named " + selection.name.value);
}
if (fragment && fragment.typeCondition) {
typeCondition = fragment.typeCondition.name.value;
if (execContext.fragmentMatcher(rootValue, typeCondition, context)) {
return [2, this.resolveSelectionSet(fragment.selectionSet, rootValue, execContext).then(function (fragmentResult) {
resultsToMerge.push(fragmentResult);
})];
}
}
return [2];
});
}); };
return [2, Promise.all(selectionSet.selections.map(execute)).then(function () {
return mergeDeepArray(resultsToMerge);
})];
});
});
};
LocalState.prototype.resolveField = function (field, rootValue, execContext) {
return __awaiter(this, void 0, void 0, function () {
var variables, fieldName, aliasedFieldName, aliasUsed, defaultResult, resultPromise, resolverType, resolverMap, resolve;
var _this = this;
return __generator(this, function (_a) {
variables = execContext.variables;
fieldName = field.name.value;
aliasedFieldName = resultKeyNameFromField(field);
aliasUsed = fieldName !== aliasedFieldName;
defaultResult = rootValue[aliasedFieldName] || rootValue[fieldName];
resultPromise = Promise.resolve(defaultResult);
if (!execContext.onlyRunForcedResolvers ||
this.shouldForceResolvers(field)) {
resolverType = rootValue.__typename || execContext.defaultOperationType;
resolverMap = this.resolvers && this.resolvers[resolverType];
if (resolverMap) {
resolve = resolverMap[aliasUsed ? fieldName : aliasedFieldName];
if (resolve) {
resultPromise = Promise.resolve(resolve(rootValue, argumentsObjectFromField(field, variables), execContext.context, { field: field, fragmentMap: execContext.fragmentMap }));
}
}
}
return [2, resultPromise.then(function (result) {
if (result === void 0) { result = defaultResult; }
if (field.directives) {
field.directives.forEach(function (directive) {
if (directive.name.value === 'export' && directive.arguments) {
directive.arguments.forEach(function (arg) {
if (arg.name.value === 'as' && arg.value.kind === 'StringValue') {
execContext.exportedVariables[arg.value.value] = result;
}
});
}
});
}
if (!field.selectionSet) {
return result;
}
if (result == null) {
return result;
}
if (Array.isArray(result)) {
return _this.resolveSubSelectedArray(field, result, execContext);
}
if (field.selectionSet) {
return _this.resolveSelectionSet(field.selectionSet, result, execContext);
}
})];
});
});
};
LocalState.prototype.resolveSubSelectedArray = function (field, result, execContext) {
var _this = this;
return Promise.all(result.map(function (item) {
if (item === null) {
return null;
}
if (Array.isArray(item)) {
return _this.resolveSubSelectedArray(field, item, execContext);
}
if (field.selectionSet) {
return _this.resolveSelectionSet(field.selectionSet, item, execContext);
}
}));
};
return LocalState;
}());
function multiplex(inner) {
var observers = new Set();
var sub = null;
return new Observable(function (observer) {
observers.add(observer);
sub = sub || inner.subscribe({
next: function (value) {
observers.forEach(function (obs) { return obs.next && obs.next(value); });
},
error: function (error) {
observers.forEach(function (obs) { return obs.error && obs.error(error); });
},
complete: function () {
observers.forEach(function (obs) { return obs.complete && obs.complete(); });
},
});
return function () {
if (observers.delete(observer) && !observers.size && sub) {
sub.unsubscribe();
sub = null;
}
};
});
}
function asyncMap(observable, mapFn) {
return new Observable(function (observer) {
var next = observer.next, error = observer.error, complete = observer.complete;
var activeNextCount = 0;
var completed = false;
var handler = {
next: function (value) {
++activeNextCount;
new Promise(function (resolve) {
resolve(mapFn(value));
}).then(function (result) {
--activeNextCount;
next && next.call(observer, result);
completed && handler.complete();
}, function (e) {
--activeNextCount;
error && error.call(observer, e);
});
},
error: function (e) {
error && error.call(observer, e);
},
complete: function () {
completed = true;
if (!activeNextCount) {
complete && complete.call(observer);
}
},
};
var sub = observable.subscribe(handler);
return function () { return sub.unsubscribe(); };
});
}
var hasOwnProperty = Object.prototype.hasOwnProperty;
var QueryManager = (function () {
function QueryManager(_a) {
var link = _a.link, _b = _a.queryDeduplication, queryDeduplication = _b === void 0 ? false : _b, store = _a.store, _c = _a.onBroadcast, onBroadcast = _c === void 0 ? function () { return undefined; } : _c, _d = _a.ssrMode, ssrMode = _d === void 0 ? false : _d, _e = _a.clientAwareness, clientAwareness = _e === void 0 ? {} : _e, localState = _a.localState, assumeImmutableResults = _a.assumeImmutableResults;
this.mutationStore = new MutationStore();
this.queryStore = new QueryStore();
this.clientAwareness = {};
this.idCounter = 1;
this.queries = new Map();
this.fetchQueryRejectFns = new Map();
this.transformCache = new (canUseWeakMap ? WeakMap : Map)();
this.inFlightLinkObservables = new Map();
this.pollingInfoByQueryId = new Map();
this.link = link;
this.queryDeduplication = queryDeduplication;
this.dataStore = store;
this.onBroadcast = onBroadcast;
this.clientAwareness = clientAwareness;
this.localState = localState || new LocalState({ cache: store.getCache() });
this.ssrMode = ssrMode;
this.assumeImmutableResults = !!assumeImmutableResults;
}
QueryManager.prototype.stop = function () {
var _this = this;
this.queries.forEach(function (_info, queryId) {
_this.stopQueryNoBroadcast(queryId);
});
this.fetchQueryRejectFns.forEach(function (reject) {
reject(process.env.NODE_ENV === "production" ? new InvariantError(8) : new InvariantError('QueryManager stopped while query was in flight'));
});
};
QueryManager.prototype.mutate = function (_a) {
var mutation = _a.mutation, variables = _a.variables, optimisticResponse = _a.optimisticResponse, updateQueriesByName = _a.updateQueries, _b = _a.refetchQueries, refetchQueries = _b === void 0 ? [] : _b, _c = _a.awaitRefetchQueries, awaitRefetchQueries = _c === void 0 ? false : _c, updateWithProxyFn = _a.update, _d = _a.errorPolicy, errorPolicy = _d === void 0 ? 'none' : _d, fetchPolicy = _a.fetchPolicy, _e = _a.context, context = _e === void 0 ? {} : _e;
return __awaiter(this, void 0, void 0, function () {
var mutationId, generateUpdateQueriesInfo, self;
var _this = this;
return __generator(this, function (_f) {
switch (_f.label) {
case 0:
process.env.NODE_ENV === "production" ? invariant(mutation, 9) : invariant(mutation, 'mutation option is required. You must specify your GraphQL document in the mutation option.');
process.env.NODE_ENV === "production" ? invariant(!fetchPolicy || fetchPolicy === 'no-cache', 10) : invariant(!fetchPolicy || fetchPolicy === 'no-cache', "Mutations only support a 'no-cache' fetchPolicy. If you don't want to disable the cache, remove your fetchPolicy setting to proceed with the default mutation behavior.");
mutationId = this.generateQueryId();
mutation = this.transform(mutation).document;
this.setQuery(mutationId, function () { return ({ document: mutation }); });
variables = this.getVariables(mutation, variables);
if (!this.transform(mutation).hasClientExports) return [3, 2];
return [4, this.localState.addExportedVariables(mutation, variables, context)];
case 1:
variables = _f.sent();
_f.label = 2;
case 2:
generateUpdateQueriesInfo = function () {
var ret = {};
if (updateQueriesByName) {
_this.queries.forEach(function (_a, queryId) {
var observableQuery = _a.observableQuery;
if (observableQuery) {
var queryName = observableQuery.queryName;
if (queryName &&
hasOwnProperty.call(updateQueriesByName, queryName)) {
ret[queryId] = {
updater: updateQueriesByName[queryName],
query: _this.queryStore.get(queryId),
};
}
}
});
}
return ret;
};
this.mutationStore.initMutation(mutationId, mutation, variables);
this.dataStore.markMutationInit({
mutationId: mutationId,
document: mutation,
variables: variables,
updateQueries: generateUpdateQueriesInfo(),
update: updateWithProxyFn,
optimisticResponse: optimisticResponse,
});
this.broadcastQueries();
self = this;
return [2, new Promise(function (resolve, reject) {
var storeResult;
var error;
self.getObservableFromLink(mutation, __assign(__assign({}, context), { optimisticResponse: optimisticResponse }), variables, false).subscribe({
next: function (result) {
if (graphQLResultHasError(result) && errorPolicy === 'none') {
error = new ApolloError({
graphQLErrors: result.errors,
});
return;
}
self.mutationStore.markMutationResult(mutationId);
if (fetchPolicy !== 'no-cache') {
self.dataStore.markMutationResult({
mutationId: mutationId,
result: result,
document: mutation,
variables: variables,
updateQueries: generateUpdateQueriesInfo(),
update: updateWithProxyFn,
});
}
storeResult = result;
},
error: function (err) {
self.mutationStore.markMutationError(mutationId, err);
self.dataStore.markMutationComplete({
mutationId: mutationId,
optimisticResponse: optimisticResponse,
});
self.broadcastQueries();
self.setQuery(mutationId, function () { return ({ document: null }); });
reject(new ApolloError({
networkError: err,
}));
},
complete: function () {
if (error) {
self.mutationStore.markMutationError(mutationId, error);
}
self.dataStore.markMutationComplete({
mutationId: mutationId,
optimisticResponse: optimisticResponse,
});
self.broadcastQueries();
if (error) {
reject(error);
return;
}
if (typeof refetchQueries === 'function') {
refetchQueries = refetchQueries(storeResult);
}
var refetchQueryPromises = [];
if (isNonEmptyArray(refetchQueries)) {
refetchQueries.forEach(functio