apollo-client
Advanced tools
Comparing version 2.4.5 to 2.5.0-alpha.1
import { ApolloLink, FetchResult, GraphQLRequest } from 'apollo-link'; | ||
import { ExecutionResult } from 'graphql'; | ||
import { ExecutionResult, DocumentNode } from 'graphql'; | ||
import { ApolloCache, DataProxy } from 'apollo-cache'; | ||
import { QueryManager } from './core/QueryManager'; | ||
import { ApolloQueryResult, OperationVariables } from './core/types'; | ||
import { ApolloQueryResult, OperationVariables, Initializers, Resolvers } from './core/types'; | ||
import { ObservableQuery } from './core/ObservableQuery'; | ||
@@ -18,7 +18,10 @@ import { Observable } from './util/Observable'; | ||
cache: ApolloCache<TCacheShape>; | ||
ssrForceFetchDelay?: number; | ||
ssrMode?: boolean; | ||
ssrForceFetchDelay?: number; | ||
connectToDevTools?: boolean; | ||
queryDeduplication?: boolean; | ||
defaultOptions?: DefaultOptions; | ||
initializers?: Initializers<TCacheShape> | Initializers<TCacheShape>[]; | ||
resolvers?: Resolvers | Resolvers[]; | ||
typeDefs?: string | string[] | DocumentNode | DocumentNode[]; | ||
}; | ||
@@ -57,4 +60,9 @@ export default class ApolloClient<TCacheShape> implements DataProxy { | ||
restore(serializedState: TCacheShape): ApolloCache<TCacheShape>; | ||
runInitializers(initializers: Initializers<TCacheShape> | Initializers<TCacheShape>[]): void; | ||
addResolvers(resolvers: Resolvers | Resolvers[]): void; | ||
getResolvers(): Resolvers; | ||
setTypeDefs(typeDefs: string | string[] | DocumentNode | DocumentNode[]): void; | ||
getTypeDefs(): string | string[] | DocumentNode | DocumentNode[] | undefined; | ||
private initProxy; | ||
} | ||
//# sourceMappingURL=ApolloClient.d.ts.map |
@@ -18,2 +18,6 @@ var __assign = (this && this.__assign) || function () { | ||
var hasSuggestedDevtools = false; | ||
var supportedDirectives = new ApolloLink(function (operation, forward) { | ||
operation.query = removeConnectionDirectiveFromDocument(operation.query); | ||
return forward(operation); | ||
}); | ||
var ApolloClient = (function () { | ||
@@ -24,17 +28,6 @@ function ApolloClient(options) { | ||
this.resetStoreCallbacks = []; | ||
var link = options.link, cache = options.cache, _a = options.ssrMode, ssrMode = _a === void 0 ? false : _a, _b = options.ssrForceFetchDelay, ssrForceFetchDelay = _b === void 0 ? 0 : _b, connectToDevTools = options.connectToDevTools, _c = options.queryDeduplication, queryDeduplication = _c === void 0 ? true : _c, defaultOptions = options.defaultOptions; | ||
var link = options.link, cache = options.cache, _a = options.ssrMode, ssrMode = _a === void 0 ? false : _a, _b = options.ssrForceFetchDelay, ssrForceFetchDelay = _b === void 0 ? 0 : _b, connectToDevTools = options.connectToDevTools, _c = options.queryDeduplication, queryDeduplication = _c === void 0 ? true : _c, defaultOptions = options.defaultOptions, initializers = options.initializers, resolvers = options.resolvers, typeDefs = options.typeDefs; | ||
if (!link || !cache) { | ||
throw new Error("\n In order to initialize Apollo Client, you must specify link & cache properties on the config object.\n This is part of the required upgrade when migrating from Apollo Client 1.0 to Apollo Client 2.0.\n For more information, please visit:\n https://www.apollographql.com/docs/react/basics/setup.html\n to help you get started.\n "); | ||
} | ||
var supportedCache = new Map(); | ||
var supportedDirectives = new ApolloLink(function (operation, forward) { | ||
var result = supportedCache.get(operation.query); | ||
if (!result) { | ||
result = removeConnectionDirectiveFromDocument(operation.query); | ||
supportedCache.set(operation.query, result); | ||
supportedCache.set(result, result); | ||
} | ||
operation.query = result; | ||
return forward(operation); | ||
}); | ||
this.link = supportedDirectives.concat(link); | ||
@@ -70,3 +63,2 @@ this.cache = cache; | ||
if (window.navigator && | ||
window.navigator.userAgent && | ||
window.navigator.userAgent.indexOf('Chrome') > -1) { | ||
@@ -81,2 +73,11 @@ console.debug('Download the Apollo DevTools ' + | ||
this.version = version; | ||
if (initializers) { | ||
this.store.initializeSync(initializers); | ||
} | ||
if (resolvers) { | ||
this.addResolvers(resolvers); | ||
} | ||
if (typeDefs) { | ||
this.setTypeDefs(typeDefs); | ||
} | ||
} | ||
@@ -209,2 +210,17 @@ ApolloClient.prototype.watchQuery = function (options) { | ||
}; | ||
ApolloClient.prototype.runInitializers = function (initializers) { | ||
this.store.initialize(initializers, this); | ||
}; | ||
ApolloClient.prototype.addResolvers = function (resolvers) { | ||
this.initQueryManager().addResolvers(resolvers); | ||
}; | ||
ApolloClient.prototype.getResolvers = function () { | ||
return this.initQueryManager().getResolvers(); | ||
}; | ||
ApolloClient.prototype.setTypeDefs = function (typeDefs) { | ||
this.initQueryManager().setTypeDefs(typeDefs); | ||
}; | ||
ApolloClient.prototype.getTypeDefs = function () { | ||
return this.queryManager ? this.queryManager.getTypeDefs() : undefined; | ||
}; | ||
ApolloClient.prototype.initProxy = function () { | ||
@@ -211,0 +227,0 @@ if (!this.proxy) { |
@@ -39,3 +39,2 @@ import { GraphQLError } from 'graphql'; | ||
private lastResult; | ||
private lastResultSnapshot; | ||
private lastError; | ||
@@ -49,3 +48,2 @@ constructor({ scheduler, options, shouldSubscribe, }: { | ||
currentResult(): ApolloCurrentResult<TData>; | ||
isDifferentFromLastResult(newResult: ApolloQueryResult<TData>): boolean; | ||
getLastResult(): ApolloQueryResult<TData>; | ||
@@ -56,3 +54,3 @@ getLastError(): ApolloError; | ||
fetchMore<K extends keyof TVariables>(fetchMoreOptions: FetchMoreQueryOptions<TVariables, K> & FetchMoreOptions<TData, TVariables>): Promise<ApolloQueryResult<TData>>; | ||
subscribeToMore<TSubscriptionData = TData>(options: SubscribeToMoreOptions<TData, TVariables, TSubscriptionData>): () => void; | ||
subscribeToMore(options: SubscribeToMoreOptions<TData, TVariables>): () => void; | ||
setOptions(opts: ModifiableWatchQueryOptions): Promise<ApolloQueryResult<TData>>; | ||
@@ -59,0 +57,0 @@ setVariables(variables: TVariables, tryFetch?: boolean, fetchResults?: boolean): Promise<ApolloQueryResult<TData>>; |
@@ -25,3 +25,3 @@ var __extends = (this && this.__extends) || (function () { | ||
}; | ||
import { isEqual, tryFunctionOrLogError, cloneDeep } from 'apollo-utilities'; | ||
import { isEqual, tryFunctionOrLogError } from 'apollo-utilities'; | ||
import { NetworkStatus, isNetworkRequestInFlight } from './networkStatus'; | ||
@@ -100,2 +100,5 @@ import { Observable } from '../util/Observable'; | ||
} | ||
if (queryStoreValue && queryStoreValue.variables) { | ||
this.options.variables = Object.assign({}, this.options.variables, queryStoreValue.variables); | ||
} | ||
var _a = this.queryManager.getCurrentQueryResult(this), data = _a.data, partial = _a.partial; | ||
@@ -124,14 +127,7 @@ var queryLoading = !queryStoreValue || | ||
if (!partial) { | ||
this.lastResult = __assign({}, result, { stale: false }); | ||
this.lastResultSnapshot = cloneDeep(this.lastResult); | ||
var stale = false; | ||
this.lastResult = __assign({}, result, { stale: stale }); | ||
} | ||
return __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 () { | ||
@@ -145,3 +141,2 @@ return this.lastResult; | ||
delete this.lastResult; | ||
delete this.lastResultSnapshot; | ||
delete this.lastError; | ||
@@ -340,3 +335,2 @@ this.isTornDown = false; | ||
_this.lastResult = result; | ||
_this.lastResultSnapshot = cloneDeep(result); | ||
_this.observers.forEach(function (obs) { return obs.next && obs.next(result); }); | ||
@@ -343,0 +337,0 @@ }, |
@@ -11,3 +11,3 @@ import { ApolloLink, FetchResult } from 'apollo-link'; | ||
import { ObservableQuery } from './ObservableQuery'; | ||
import { QueryListener, ApolloQueryResult, FetchType, OperationVariables } from './types'; | ||
import { QueryListener, ApolloQueryResult, FetchType, OperationVariables, Resolvers } from './types'; | ||
export interface QueryInfo { | ||
@@ -40,2 +40,4 @@ listeners: QueryListener[]; | ||
private queryIdsByName; | ||
private resolvers; | ||
private typeDefs; | ||
constructor({ link, queryDeduplication, store, onBroadcast, ssrMode, }: { | ||
@@ -78,2 +80,6 @@ link: ApolloLink; | ||
broadcastQueries(): void; | ||
addResolvers(resolvers: Resolvers | Resolvers[]): void; | ||
getResolvers(): Resolvers; | ||
setTypeDefs(typeDefs: string | string[] | DocumentNode | DocumentNode[]): void; | ||
getTypeDefs(): string | string[] | DocumentNode | DocumentNode[]; | ||
private getObservableQueryPromises; | ||
@@ -87,3 +93,7 @@ private fetchRequest; | ||
private buildOperationForLink; | ||
private contextCopyWithCache; | ||
private prepareResolver; | ||
private prepareClientExportVariables; | ||
private resolveDocumentLocally; | ||
} | ||
//# sourceMappingURL=QueryManager.d.ts.map |
@@ -48,8 +48,11 @@ var __assign = (this && this.__assign) || function () { | ||
import { execute, ApolloLink } from 'apollo-link'; | ||
import { graphqlAsync as graphql } from 'graphql-anywhere'; | ||
import { print } from 'graphql/language/printer'; | ||
import { DedupLink as Deduplicator } from 'apollo-link-dedup'; | ||
import { assign, getDefaultValues, getMutationDefinition, getOperationDefinition, getOperationName, getQueryDefinition, isProduction, hasDirectives, } from 'apollo-utilities'; | ||
import { assign, getDefaultValues, getMutationDefinition, getOperationDefinition, getOperationName, getQueryDefinition, getMainDefinition, isProduction, hasDirectives, mergeDeep, getDirectivesFromDocument, getDirectiveInfoFromField, flattenSelections, } from 'apollo-utilities'; | ||
import { QueryScheduler } from '../scheduler/scheduler'; | ||
import { isApolloError, ApolloError } from '../errors/ApolloError'; | ||
import { Observable } from '../util/Observable'; | ||
import { removeClientSetsFromDocument } from '../util/removeClientSetsFromDocument'; | ||
import { capitalizeFirstLetter } from '../util/capitalizeFirstLetter'; | ||
import { MutationStore } from '../data/mutations'; | ||
@@ -61,2 +64,11 @@ import { QueryStore } from '../data/queries'; | ||
import { graphQLResultHasError } from 'apollo-utilities'; | ||
var defaultQueryInfo = { | ||
listeners: [], | ||
invalidated: false, | ||
document: null, | ||
newData: null, | ||
lastRequestId: null, | ||
observableQuery: null, | ||
subscriptions: [], | ||
}; | ||
var QueryManager = (function () { | ||
@@ -71,2 +83,3 @@ function QueryManager(_a) { | ||
this.queryIdsByName = {}; | ||
this.resolvers = {}; | ||
this.link = link; | ||
@@ -80,133 +93,193 @@ this.deduplicator = ApolloLink.from([new Deduplicator(), link]); | ||
QueryManager.prototype.mutate = function (_a) { | ||
var _this = this; | ||
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; | ||
if (!mutation) { | ||
throw new Error('mutation option is required. You must specify your GraphQL document in the mutation option.'); | ||
} | ||
if (fetchPolicy && fetchPolicy !== 'no-cache') { | ||
throw new Error("fetchPolicy for mutations currently only supports the 'no-cache' policy"); | ||
} | ||
var mutationId = this.generateQueryId(); | ||
var cache = this.dataStore.getCache(); | ||
(mutation = cache.transformDocument(mutation)), | ||
(variables = assign({}, getDefaultValues(getMutationDefinition(mutation)), variables)); | ||
var mutationString = print(mutation); | ||
this.setQuery(mutationId, function () { return ({ document: mutation }); }); | ||
var generateUpdateQueriesInfo = function () { | ||
var ret = {}; | ||
if (updateQueriesByName) { | ||
Object.keys(updateQueriesByName).forEach(function (queryName) { | ||
return (_this.queryIdsByName[queryName] || []).forEach(function (queryId) { | ||
ret[queryId] = { | ||
updater: updateQueriesByName[queryName], | ||
query: _this.queryStore.get(queryId), | ||
return __awaiter(this, void 0, void 0, function () { | ||
var mutationId, cache, mutationString, generateUpdateQueriesInfo, updatedVariables; | ||
var _this = this; | ||
return __generator(this, function (_f) { | ||
switch (_f.label) { | ||
case 0: | ||
if (!mutation) { | ||
throw new Error('mutation option is required. You must specify your GraphQL document in the mutation option.'); | ||
} | ||
if (fetchPolicy && fetchPolicy !== 'no-cache') { | ||
throw new Error("fetchPolicy for mutations currently only supports the 'no-cache' policy"); | ||
} | ||
mutationId = this.generateQueryId(); | ||
cache = this.dataStore.getCache(); | ||
(mutation = cache.transformDocument(mutation)), | ||
(variables = assign({}, getDefaultValues(getMutationDefinition(mutation)), variables)); | ||
mutationString = print(mutation); | ||
this.setQuery(mutationId, function () { return ({ document: mutation }); }); | ||
generateUpdateQueriesInfo = function () { | ||
var ret = {}; | ||
if (updateQueriesByName) { | ||
Object.keys(updateQueriesByName).forEach(function (queryName) { | ||
return (_this.queryIdsByName[queryName] || []).forEach(function (queryId) { | ||
ret[queryId] = { | ||
updater: updateQueriesByName[queryName], | ||
query: _this.queryStore.get(queryId), | ||
}; | ||
}); | ||
}); | ||
} | ||
return ret; | ||
}; | ||
}); | ||
}); | ||
} | ||
return ret; | ||
}; | ||
this.mutationStore.initMutation(mutationId, mutationString, variables); | ||
this.dataStore.markMutationInit({ | ||
mutationId: mutationId, | ||
document: mutation, | ||
variables: variables || {}, | ||
updateQueries: generateUpdateQueriesInfo(), | ||
update: updateWithProxyFn, | ||
optimisticResponse: optimisticResponse, | ||
}); | ||
this.broadcastQueries(); | ||
return new Promise(function (resolve, reject) { | ||
var storeResult; | ||
var error; | ||
var operation = _this.buildOperationForLink(mutation, variables, __assign({}, context, { optimisticResponse: optimisticResponse })); | ||
var completeMutation = function () { return __awaiter(_this, void 0, void 0, function () { | ||
var refetchQueryPromises, _i, refetchQueries_1, refetchQuery, promise, queryOptions; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (error) { | ||
this.mutationStore.markMutationError(mutationId, error); | ||
} | ||
this.dataStore.markMutationComplete({ | ||
mutationId: mutationId, | ||
optimisticResponse: optimisticResponse, | ||
}); | ||
this.broadcastQueries(); | ||
if (error) { | ||
throw error; | ||
} | ||
if (typeof refetchQueries === 'function') { | ||
refetchQueries = refetchQueries(storeResult); | ||
} | ||
refetchQueryPromises = []; | ||
for (_i = 0, refetchQueries_1 = refetchQueries; _i < refetchQueries_1.length; _i++) { | ||
refetchQuery = refetchQueries_1[_i]; | ||
if (typeof refetchQuery === 'string') { | ||
promise = this.refetchQueryByName(refetchQuery); | ||
if (promise) { | ||
refetchQueryPromises.push(promise); | ||
} | ||
continue; | ||
} | ||
queryOptions = { | ||
query: refetchQuery.query, | ||
variables: refetchQuery.variables, | ||
fetchPolicy: 'network-only', | ||
}; | ||
if (refetchQuery.context) { | ||
queryOptions.context = refetchQuery.context; | ||
} | ||
refetchQueryPromises.push(this.query(queryOptions)); | ||
} | ||
if (!awaitRefetchQueries) return [3, 2]; | ||
return [4, Promise.all(refetchQueryPromises)]; | ||
case 1: | ||
_a.sent(); | ||
_a.label = 2; | ||
case 2: | ||
this.setQuery(mutationId, function () { return ({ document: undefined }); }); | ||
if (errorPolicy === 'ignore' && | ||
storeResult && | ||
graphQLResultHasError(storeResult)) { | ||
delete storeResult.errors; | ||
} | ||
return [2, storeResult]; | ||
} | ||
}); | ||
}); }; | ||
execute(_this.link, operation).subscribe({ | ||
next: function (result) { | ||
if (graphQLResultHasError(result) && errorPolicy === 'none') { | ||
error = new ApolloError({ | ||
graphQLErrors: result.errors, | ||
}); | ||
return; | ||
} | ||
_this.mutationStore.markMutationResult(mutationId); | ||
if (fetchPolicy !== 'no-cache') { | ||
_this.dataStore.markMutationResult({ | ||
return [4, this.prepareClientExportVariables(mutation, variables, context)]; | ||
case 1: | ||
updatedVariables = _f.sent(); | ||
this.mutationStore.initMutation(mutationId, mutationString, updatedVariables); | ||
this.dataStore.markMutationInit({ | ||
mutationId: mutationId, | ||
result: result, | ||
document: mutation, | ||
variables: variables || {}, | ||
variables: updatedVariables || {}, | ||
updateQueries: generateUpdateQueriesInfo(), | ||
update: updateWithProxyFn, | ||
optimisticResponse: optimisticResponse, | ||
}); | ||
} | ||
storeResult = result; | ||
}, | ||
error: function (err) { | ||
_this.mutationStore.markMutationError(mutationId, err); | ||
_this.dataStore.markMutationComplete({ | ||
mutationId: mutationId, | ||
optimisticResponse: optimisticResponse, | ||
}); | ||
_this.broadcastQueries(); | ||
_this.setQuery(mutationId, function () { return ({ document: undefined }); }); | ||
reject(new ApolloError({ | ||
networkError: err, | ||
})); | ||
}, | ||
complete: function () { return completeMutation().then(resolve, reject); }, | ||
this.broadcastQueries(); | ||
return [2, new Promise(function (resolve, reject) { | ||
var storeResult; | ||
var error; | ||
var operation = _this.buildOperationForLink(mutation, updatedVariables, __assign({}, context, { optimisticResponse: optimisticResponse })); | ||
var completeMutation = function () { return __awaiter(_this, void 0, void 0, function () { | ||
var refetchQueryPromises, _i, refetchQueries_1, refetchQuery, promise, queryOptions; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (error) { | ||
this.mutationStore.markMutationError(mutationId, error); | ||
} | ||
this.dataStore.markMutationComplete({ | ||
mutationId: mutationId, | ||
optimisticResponse: optimisticResponse, | ||
}); | ||
this.broadcastQueries(); | ||
if (error) { | ||
throw error; | ||
} | ||
if (typeof refetchQueries === 'function') { | ||
refetchQueries = refetchQueries(storeResult); | ||
} | ||
refetchQueryPromises = []; | ||
for (_i = 0, refetchQueries_1 = refetchQueries; _i < refetchQueries_1.length; _i++) { | ||
refetchQuery = refetchQueries_1[_i]; | ||
if (typeof refetchQuery === 'string') { | ||
promise = this.refetchQueryByName(refetchQuery); | ||
if (promise) { | ||
refetchQueryPromises.push(promise); | ||
} | ||
continue; | ||
} | ||
queryOptions = { | ||
query: refetchQuery.query, | ||
variables: refetchQuery.variables, | ||
fetchPolicy: 'network-only', | ||
}; | ||
if (refetchQuery.context) { | ||
queryOptions.context = refetchQuery.context; | ||
} | ||
refetchQueryPromises.push(this.query(queryOptions)); | ||
} | ||
if (!awaitRefetchQueries) return [3, 2]; | ||
return [4, Promise.all(refetchQueryPromises)]; | ||
case 1: | ||
_a.sent(); | ||
_a.label = 2; | ||
case 2: | ||
this.setQuery(mutationId, function () { return ({ document: undefined }); }); | ||
if (errorPolicy === 'ignore' && | ||
storeResult && | ||
graphQLResultHasError(storeResult)) { | ||
delete storeResult.errors; | ||
} | ||
return [2, storeResult]; | ||
} | ||
}); | ||
}); }; | ||
var clientQuery = null; | ||
var serverQuery; | ||
if (hasDirectives(['client'], operation.query)) { | ||
clientQuery = operation.query; | ||
serverQuery = removeClientSetsFromDocument(operation.query); | ||
} | ||
else { | ||
serverQuery = operation.query; | ||
} | ||
if (serverQuery) { | ||
operation.query = serverQuery; | ||
} | ||
var obs = serverQuery | ||
? execute(_this.link, operation) | ||
: Observable.of({ | ||
data: {}, | ||
}); | ||
var complete = false; | ||
var handlingNext = false; | ||
obs.subscribe({ | ||
next: function (result) { return __awaiter(_this, void 0, void 0, function () { | ||
var updatedResult, resolver, context_1, variables_1, localResult; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
handlingNext = true; | ||
if (graphQLResultHasError(result) && errorPolicy === 'none') { | ||
error = new ApolloError({ | ||
graphQLErrors: result.errors, | ||
}); | ||
return [2]; | ||
} | ||
this.mutationStore.markMutationResult(mutationId); | ||
updatedResult = result; | ||
if (!clientQuery) return [3, 2]; | ||
resolver = this.prepareResolver(clientQuery); | ||
if (!resolver) return [3, 2]; | ||
context_1 = operation.context, variables_1 = operation.variables; | ||
return [4, graphql(resolver, clientQuery, result.data, context_1, variables_1)]; | ||
case 1: | ||
localResult = _a.sent(); | ||
if (localResult) { | ||
updatedResult.data = __assign({}, updatedResult.data, localResult); | ||
} | ||
_a.label = 2; | ||
case 2: | ||
if (fetchPolicy !== 'no-cache') { | ||
this.dataStore.markMutationResult({ | ||
mutationId: mutationId, | ||
result: updatedResult, | ||
document: mutation, | ||
variables: updatedVariables || {}, | ||
updateQueries: generateUpdateQueriesInfo(), | ||
update: updateWithProxyFn, | ||
}); | ||
} | ||
storeResult = updatedResult; | ||
handlingNext = false; | ||
if (complete) { | ||
completeMutation().then(resolve, reject); | ||
} | ||
return [2]; | ||
} | ||
}); | ||
}); }, | ||
error: function (err) { | ||
this.mutationStore.markMutationError(mutationId, err); | ||
this.dataStore.markMutationComplete({ | ||
mutationId: mutationId, | ||
optimisticResponse: optimisticResponse, | ||
}); | ||
this.broadcastQueries(); | ||
this.setQuery(mutationId, function () { return ({ document: undefined }); }); | ||
reject(new ApolloError({ | ||
networkError: err, | ||
})); | ||
}, | ||
complete: function () { | ||
if (!handlingNext) { | ||
completeMutation().then(resolve, reject); | ||
} | ||
complete = true; | ||
}, | ||
}); | ||
})]; | ||
} | ||
}); | ||
@@ -216,79 +289,90 @@ }); | ||
QueryManager.prototype.fetchQuery = function (queryId, options, fetchType, fetchMoreForQueryId) { | ||
var _this = this; | ||
var _a = options.variables, variables = _a === void 0 ? {} : _a, _b = options.metadata, metadata = _b === void 0 ? null : _b, _c = options.fetchPolicy, fetchPolicy = _c === void 0 ? 'cache-first' : _c; | ||
var cache = this.dataStore.getCache(); | ||
var query = cache.transformDocument(options.query); | ||
var storeResult; | ||
var needToFetch = fetchPolicy === 'network-only' || fetchPolicy === 'no-cache'; | ||
if (fetchType !== FetchType.refetch && | ||
fetchPolicy !== 'network-only' && | ||
fetchPolicy !== 'no-cache') { | ||
var _d = this.dataStore.getCache().diff({ | ||
query: query, | ||
variables: variables, | ||
returnPartialData: true, | ||
optimistic: false, | ||
}), complete = _d.complete, result = _d.result; | ||
needToFetch = !complete || fetchPolicy === 'cache-and-network'; | ||
storeResult = result; | ||
} | ||
var shouldFetch = needToFetch && fetchPolicy !== 'cache-only' && fetchPolicy !== 'standby'; | ||
if (hasDirectives(['live'], query)) | ||
shouldFetch = true; | ||
var requestId = this.generateRequestId(); | ||
var cancel = this.updateQueryWatch(queryId, query, options); | ||
this.setQuery(queryId, function () { return ({ | ||
document: query, | ||
lastRequestId: requestId, | ||
invalidated: true, | ||
cancel: cancel, | ||
}); }); | ||
this.invalidate(true, fetchMoreForQueryId); | ||
this.queryStore.initQuery({ | ||
queryId: queryId, | ||
document: query, | ||
storePreviousVariables: shouldFetch, | ||
variables: variables, | ||
isPoll: fetchType === FetchType.poll, | ||
isRefetch: fetchType === FetchType.refetch, | ||
metadata: metadata, | ||
fetchMoreForQueryId: fetchMoreForQueryId, | ||
}); | ||
this.broadcastQueries(); | ||
var shouldDispatchClientResult = !shouldFetch || fetchPolicy === 'cache-and-network'; | ||
if (shouldDispatchClientResult) { | ||
this.queryStore.markQueryResultClient(queryId, !shouldFetch); | ||
this.invalidate(true, queryId, fetchMoreForQueryId); | ||
this.broadcastQueries(); | ||
} | ||
if (shouldFetch) { | ||
var networkResult = this.fetchRequest({ | ||
requestId: requestId, | ||
queryId: queryId, | ||
document: query, | ||
options: options, | ||
fetchMoreForQueryId: fetchMoreForQueryId, | ||
}).catch(function (error) { | ||
if (isApolloError(error)) { | ||
throw error; | ||
return __awaiter(this, void 0, void 0, function () { | ||
var _a, variables, _b, metadata, _c, fetchPolicy, _d, context, cache, query, updatedVariables, updatedOptions, storeResult, needToFetch, _e, complete, result, shouldFetch, requestId, cancel, shouldDispatchClientResult, networkResult; | ||
var _this = this; | ||
return __generator(this, function (_f) { | ||
switch (_f.label) { | ||
case 0: | ||
_a = options.variables, variables = _a === void 0 ? {} : _a, _b = options.metadata, metadata = _b === void 0 ? null : _b, _c = options.fetchPolicy, fetchPolicy = _c === void 0 ? 'cache-first' : _c, _d = options.context, context = _d === void 0 ? {} : _d; | ||
cache = this.dataStore.getCache(); | ||
query = cache.transformDocument(options.query); | ||
return [4, this.prepareClientExportVariables(query, variables, context)]; | ||
case 1: | ||
updatedVariables = _f.sent(); | ||
updatedOptions = __assign({}, options, { variables: updatedVariables }); | ||
needToFetch = fetchPolicy === 'network-only' || fetchPolicy === 'no-cache'; | ||
if (fetchType !== FetchType.refetch && | ||
fetchPolicy !== 'network-only' && | ||
fetchPolicy !== 'no-cache') { | ||
_e = this.dataStore.getCache().diff({ | ||
query: query, | ||
variables: updatedVariables, | ||
returnPartialData: true, | ||
optimistic: false, | ||
}), complete = _e.complete, result = _e.result; | ||
needToFetch = !complete || fetchPolicy === 'cache-and-network'; | ||
storeResult = result; | ||
} | ||
shouldFetch = needToFetch && fetchPolicy !== 'cache-only' && fetchPolicy !== 'standby'; | ||
if (hasDirectives(['live'], query)) | ||
shouldFetch = true; | ||
requestId = this.generateRequestId(); | ||
cancel = this.updateQueryWatch(queryId, query, updatedOptions); | ||
this.setQuery(queryId, function () { return ({ | ||
document: query, | ||
lastRequestId: requestId, | ||
invalidated: true, | ||
cancel: cancel, | ||
}); }); | ||
this.invalidate(true, fetchMoreForQueryId); | ||
this.queryStore.initQuery({ | ||
queryId: queryId, | ||
document: query, | ||
storePreviousVariables: shouldFetch, | ||
variables: updatedVariables, | ||
isPoll: fetchType === FetchType.poll, | ||
isRefetch: fetchType === FetchType.refetch, | ||
metadata: metadata, | ||
fetchMoreForQueryId: fetchMoreForQueryId, | ||
}); | ||
this.broadcastQueries(); | ||
shouldDispatchClientResult = !shouldFetch || fetchPolicy === 'cache-and-network'; | ||
if (shouldDispatchClientResult) { | ||
this.queryStore.markQueryResultClient(queryId, !shouldFetch); | ||
this.invalidate(true, queryId, fetchMoreForQueryId); | ||
this.broadcastQueries(); | ||
} | ||
if (shouldFetch) { | ||
networkResult = this.fetchRequest({ | ||
requestId: requestId, | ||
queryId: queryId, | ||
document: query, | ||
options: updatedOptions, | ||
fetchMoreForQueryId: fetchMoreForQueryId, | ||
}).catch(function (error) { | ||
if (isApolloError(error)) { | ||
throw error; | ||
} | ||
else { | ||
var lastRequestId = _this.getQuery(queryId).lastRequestId; | ||
if (requestId >= (lastRequestId || 1)) { | ||
_this.queryStore.markQueryError(queryId, error, fetchMoreForQueryId); | ||
_this.invalidate(true, queryId, fetchMoreForQueryId); | ||
_this.broadcastQueries(); | ||
} | ||
_this.removeFetchQueryPromise(requestId); | ||
throw new ApolloError({ networkError: error }); | ||
} | ||
}); | ||
if (fetchPolicy !== 'cache-and-network') { | ||
return [2, networkResult]; | ||
} | ||
else { | ||
networkResult.catch(function () { }); | ||
} | ||
} | ||
return [2, Promise.resolve({ data: storeResult })]; | ||
} | ||
else { | ||
var lastRequestId = _this.getQuery(queryId).lastRequestId; | ||
if (requestId >= (lastRequestId || 1)) { | ||
_this.queryStore.markQueryError(queryId, error, fetchMoreForQueryId); | ||
_this.invalidate(true, queryId, fetchMoreForQueryId); | ||
_this.broadcastQueries(); | ||
} | ||
_this.removeFetchQueryPromise(requestId); | ||
throw new ApolloError({ networkError: error }); | ||
} | ||
}); | ||
if (fetchPolicy !== 'cache-and-network') { | ||
return networkResult; | ||
} | ||
else { | ||
networkResult.catch(function () { }); | ||
} | ||
} | ||
return Promise.resolve({ data: storeResult }); | ||
}); | ||
}; | ||
@@ -408,5 +492,8 @@ QueryManager.prototype.queryListenerForObserver = function (queryId, options, observer) { | ||
if (observer.next) { | ||
if (previouslyHadError || | ||
!observableQuery || | ||
observableQuery.isDifferentFromLastResult(resultFromStore)) { | ||
var isDifferentResult = !(lastResult && | ||
resultFromStore && | ||
lastResult.networkStatus === resultFromStore.networkStatus && | ||
lastResult.stale === resultFromStore.stale && | ||
lastResult.data === resultFromStore.data); | ||
if (isDifferentResult || previouslyHadError) { | ||
try { | ||
@@ -602,2 +689,3 @@ observer.next(resultFromStore); | ||
var variables = assign({}, getDefaultValues(getOperationDefinition(query)), options.variables); | ||
var updatedVariables = variables; | ||
var sub; | ||
@@ -608,19 +696,47 @@ var observers = []; | ||
if (observers.length === 1) { | ||
var handler = { | ||
next: function (result) { | ||
if (isCacheEnabled) { | ||
_this.dataStore.markSubscriptionResult(result, transformedDoc, variables); | ||
_this.broadcastQueries(); | ||
} | ||
observers.forEach(function (obs) { | ||
if (graphQLResultHasError(result) && obs.error) { | ||
obs.error(new ApolloError({ | ||
graphQLErrors: result.errors, | ||
})); | ||
var clientQuery_1 = null; | ||
var serverQuery_1; | ||
if (hasDirectives(['client'], transformedDoc)) { | ||
clientQuery_1 = transformedDoc; | ||
serverQuery_1 = removeClientSetsFromDocument(transformedDoc); | ||
} | ||
else { | ||
serverQuery_1 = transformedDoc; | ||
} | ||
var handler_1 = { | ||
next: function (result) { return __awaiter(_this, void 0, void 0, function () { | ||
var updatedResult, resolver, localResult; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
updatedResult = result; | ||
if (!clientQuery_1) return [3, 2]; | ||
resolver = this.prepareResolver(clientQuery_1); | ||
if (!resolver) return [3, 2]; | ||
return [4, graphql(resolver, clientQuery_1, result.data, {}, variables)]; | ||
case 1: | ||
localResult = _a.sent(); | ||
if (localResult) { | ||
updatedResult.data = __assign({}, updatedResult.data, localResult); | ||
} | ||
_a.label = 2; | ||
case 2: | ||
if (isCacheEnabled) { | ||
this.dataStore.markSubscriptionResult(updatedResult, transformedDoc, updatedVariables); | ||
this.broadcastQueries(); | ||
} | ||
observers.forEach(function (obs) { | ||
if (graphQLResultHasError(updatedResult) && obs.error) { | ||
obs.error(new ApolloError({ | ||
graphQLErrors: updatedResult.errors, | ||
})); | ||
} | ||
else if (obs.next) { | ||
obs.next(updatedResult); | ||
} | ||
}); | ||
return [2]; | ||
} | ||
else if (obs.next) { | ||
obs.next(result); | ||
} | ||
}); | ||
}, | ||
}); }, | ||
error: function (error) { | ||
@@ -634,4 +750,20 @@ observers.forEach(function (obs) { | ||
}; | ||
var operation = _this.buildOperationForLink(transformedDoc, variables); | ||
sub = execute(_this.link, operation).subscribe(handler); | ||
(function () { return __awaiter(_this, void 0, void 0, function () { | ||
var updatedVariables, operation; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4, this.prepareClientExportVariables(transformedDoc, variables)]; | ||
case 1: | ||
updatedVariables = _a.sent(); | ||
if (serverQuery_1) { | ||
operation = this.buildOperationForLink(serverQuery_1, updatedVariables); | ||
sub = execute(this.link, operation).subscribe(handler_1); | ||
} | ||
else { | ||
sub = Observable.of({ data: {} }).subscribe(handler_1); | ||
} | ||
return [2]; | ||
} | ||
}); | ||
}); })(); | ||
} | ||
@@ -660,3 +792,3 @@ return function () { | ||
var newData = this.getQuery(observableQuery.queryId).newData; | ||
if (newData && newData.complete) { | ||
if (newData) { | ||
return { data: newData.result, partial: false }; | ||
@@ -712,2 +844,22 @@ } | ||
}; | ||
QueryManager.prototype.addResolvers = function (resolvers) { | ||
var _this = this; | ||
if (Array.isArray(resolvers)) { | ||
resolvers.forEach(function (resolverGroup) { | ||
_this.resolvers = mergeDeep(_this.resolvers, resolverGroup); | ||
}); | ||
} | ||
else { | ||
this.resolvers = mergeDeep(this.resolvers, resolvers); | ||
} | ||
}; | ||
QueryManager.prototype.getResolvers = function () { | ||
return this.resolvers; | ||
}; | ||
QueryManager.prototype.setTypeDefs = function (typeDefs) { | ||
this.typeDefs = typeDefs; | ||
}; | ||
QueryManager.prototype.getTypeDefs = function () { | ||
return this.typeDefs; | ||
}; | ||
QueryManager.prototype.getObservableQueryPromises = function (includeStandby) { | ||
@@ -735,3 +887,22 @@ var _this = this; | ||
var variables = options.variables, context = options.context, _b = options.errorPolicy, errorPolicy = _b === void 0 ? 'none' : _b, fetchPolicy = options.fetchPolicy; | ||
var operation = this.buildOperationForLink(document, variables, __assign({}, context, { forceFetch: !this.queryDeduplication })); | ||
var clientQuery = null; | ||
var serverQuery; | ||
if (hasDirectives(['client'], document)) { | ||
clientQuery = document; | ||
serverQuery = removeClientSetsFromDocument(document); | ||
} | ||
else { | ||
serverQuery = document; | ||
} | ||
var obs; | ||
var updatedContext = {}; | ||
if (serverQuery) { | ||
var operation = this.buildOperationForLink(serverQuery, variables, __assign({}, context, { forceFetch: !this.queryDeduplication })); | ||
updatedContext = operation.context; | ||
obs = execute(this.deduplicator, operation); | ||
} | ||
else { | ||
updatedContext = this.contextCopyWithCache(context); | ||
obs = Observable.of({ data: {} }); | ||
} | ||
var resultFromStore; | ||
@@ -741,47 +912,74 @@ var errorsFromStore; | ||
_this.addFetchQueryPromise(requestId, resolve, reject); | ||
var subscription = execute(_this.deduplicator, operation).subscribe({ | ||
next: function (result) { | ||
var lastRequestId = _this.getQuery(queryId).lastRequestId; | ||
if (requestId >= (lastRequestId || 1)) { | ||
if (fetchPolicy !== 'no-cache') { | ||
try { | ||
_this.dataStore.markQueryResult(result, document, variables, fetchMoreForQueryId, errorPolicy === 'ignore' || errorPolicy === 'all'); | ||
} | ||
catch (e) { | ||
reject(e); | ||
return; | ||
} | ||
var complete = false; | ||
var handlingNext = true; | ||
var subscriber = { | ||
next: function (result) { return __awaiter(_this, void 0, void 0, function () { | ||
var updatedResult, lastRequestId, resolver, localResult; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
handlingNext = true; | ||
updatedResult = result; | ||
lastRequestId = this.getQuery(queryId).lastRequestId; | ||
if (!(requestId >= (lastRequestId || 1))) return [3, 3]; | ||
if (!clientQuery) return [3, 2]; | ||
resolver = this.prepareResolver(clientQuery); | ||
if (!resolver) return [3, 2]; | ||
return [4, graphql(resolver, clientQuery, result.data, updatedContext, variables)]; | ||
case 1: | ||
localResult = _a.sent(); | ||
if (localResult) { | ||
updatedResult.data = __assign({}, updatedResult.data, localResult); | ||
} | ||
_a.label = 2; | ||
case 2: | ||
if (fetchPolicy !== 'no-cache') { | ||
try { | ||
this.dataStore.markQueryResult(updatedResult, document, variables, fetchMoreForQueryId, errorPolicy === 'ignore' || errorPolicy === 'all'); | ||
} | ||
catch (e) { | ||
reject(e); | ||
return [2]; | ||
} | ||
} | ||
else { | ||
this.setQuery(queryId, function () { return ({ | ||
newData: { result: updatedResult.data, complete: true }, | ||
}); }); | ||
} | ||
this.queryStore.markQueryResult(queryId, updatedResult, fetchMoreForQueryId); | ||
this.invalidate(true, queryId, fetchMoreForQueryId); | ||
this.broadcastQueries(); | ||
_a.label = 3; | ||
case 3: | ||
if (updatedResult.errors && errorPolicy === 'none') { | ||
reject(new ApolloError({ | ||
graphQLErrors: updatedResult.errors, | ||
})); | ||
return [2]; | ||
} | ||
else if (errorPolicy === 'all') { | ||
errorsFromStore = updatedResult.errors; | ||
} | ||
if (fetchMoreForQueryId || fetchPolicy === 'no-cache') { | ||
resultFromStore = updatedResult.data; | ||
} | ||
else { | ||
try { | ||
resultFromStore = this.dataStore.getCache().read({ | ||
variables: variables, | ||
query: document, | ||
optimistic: false, | ||
}); | ||
} | ||
catch (e) { } | ||
} | ||
handlingNext = false; | ||
if (complete) { | ||
subscriber.complete(); | ||
} | ||
return [2]; | ||
} | ||
else { | ||
_this.setQuery(queryId, function () { return ({ | ||
newData: { result: result.data, complete: true }, | ||
}); }); | ||
} | ||
_this.queryStore.markQueryResult(queryId, result, fetchMoreForQueryId); | ||
_this.invalidate(true, queryId, fetchMoreForQueryId); | ||
_this.broadcastQueries(); | ||
} | ||
if (result.errors && errorPolicy === 'none') { | ||
reject(new ApolloError({ | ||
graphQLErrors: result.errors, | ||
})); | ||
return; | ||
} | ||
else if (errorPolicy === 'all') { | ||
errorsFromStore = result.errors; | ||
} | ||
if (fetchMoreForQueryId || fetchPolicy === 'no-cache') { | ||
resultFromStore = result.data; | ||
} | ||
else { | ||
try { | ||
resultFromStore = _this.dataStore.getCache().read({ | ||
variables: variables, | ||
query: document, | ||
optimistic: false, | ||
}); | ||
} | ||
catch (e) { } | ||
} | ||
}, | ||
}); | ||
}); }, | ||
error: function (error) { | ||
@@ -798,18 +996,22 @@ _this.removeFetchQueryPromise(requestId); | ||
complete: function () { | ||
_this.removeFetchQueryPromise(requestId); | ||
_this.setQuery(queryId, function (_a) { | ||
var subscriptions = _a.subscriptions; | ||
return ({ | ||
subscriptions: subscriptions.filter(function (x) { return x !== subscription; }), | ||
if (!handlingNext) { | ||
_this.removeFetchQueryPromise(requestId); | ||
_this.setQuery(queryId, function (_a) { | ||
var subscriptions = _a.subscriptions; | ||
return ({ | ||
subscriptions: subscriptions.filter(function (x) { return x !== subscription; }), | ||
}); | ||
}); | ||
}); | ||
resolve({ | ||
data: resultFromStore, | ||
errors: errorsFromStore, | ||
loading: false, | ||
networkStatus: NetworkStatus.ready, | ||
stale: false, | ||
}); | ||
resolve({ | ||
data: resultFromStore, | ||
errors: errorsFromStore, | ||
loading: false, | ||
networkStatus: NetworkStatus.ready, | ||
stale: false, | ||
}); | ||
} | ||
complete = true; | ||
}, | ||
}); | ||
}; | ||
var subscription = obs.subscribe(subscriber); | ||
_this.setQuery(queryId, function (_a) { | ||
@@ -839,11 +1041,3 @@ var subscriptions = _a.subscriptions; | ||
QueryManager.prototype.getQuery = function (queryId) { | ||
return this.queries.get(queryId) || { | ||
listeners: [], | ||
invalidated: false, | ||
document: null, | ||
newData: null, | ||
lastRequestId: null, | ||
observableQuery: null, | ||
subscriptions: [], | ||
}; | ||
return this.queries.get(queryId) || __assign({}, defaultQueryInfo); | ||
}; | ||
@@ -870,12 +1064,138 @@ QueryManager.prototype.setQuery = function (queryId, updater) { | ||
operationName: getOperationName(document) || undefined, | ||
context: __assign({}, extraContext, { cache: cache, getCacheKey: function (obj) { | ||
if (cache.config) { | ||
return cache.config.dataIdFromObject(obj); | ||
} | ||
else { | ||
throw new Error('To use context.getCacheKey, you need to use a cache that has a configurable dataIdFromObject, like apollo-cache-inmemory.'); | ||
} | ||
} }), | ||
context: this.contextCopyWithCache(extraContext), | ||
}; | ||
}; | ||
QueryManager.prototype.contextCopyWithCache = function (context) { | ||
if (context === void 0) { context = {}; } | ||
var cache = this.dataStore.getCache(); | ||
return __assign({}, context, { cache: cache, getCacheKey: function (obj) { | ||
if (cache.config) { | ||
return cache.config.dataIdFromObject(obj); | ||
} | ||
else { | ||
throw new Error('To use context.getCacheKey, you need to use a cache that has ' + | ||
'a configurable dataIdFromObject, like apollo-cache-inmemory.'); | ||
} | ||
} }); | ||
}; | ||
QueryManager.prototype.prepareResolver = function (query, readOnly) { | ||
if (readOnly === void 0) { readOnly = false; } | ||
var resolver = null; | ||
if (!query) { | ||
return resolver; | ||
} | ||
var definition = getMainDefinition(query); | ||
var definitionOperation = definition.operation; | ||
var type = definitionOperation | ||
? capitalizeFirstLetter(definitionOperation) | ||
: 'Query'; | ||
if (readOnly && type === 'Mutation') { | ||
type = null; | ||
} | ||
var resolvers = this.resolvers; | ||
var cache = this.dataStore.getCache(); | ||
var cacheData = cache.extract(); | ||
var _a = this, queryFn = _a.query, mutateFn = _a.mutate; | ||
resolver = function (fieldName, rootValue, args, context, info) { | ||
if (rootValue === void 0) { rootValue = {}; } | ||
var resultKey = info.resultKey; | ||
var childRootValue = {}; | ||
var rootValueKey = Object.keys(rootValue)[0]; | ||
if (rootValueKey) { | ||
childRootValue = rootValue[rootValueKey]; | ||
} | ||
var normalNode = rootValue[fieldName] !== undefined | ||
? rootValue[fieldName] | ||
: childRootValue[fieldName]; | ||
var aliasedNode = rootValue[resultKey] !== undefined | ||
? rootValue[resultKey] | ||
: childRootValue[resultKey]; | ||
var aliasUsed = resultKey !== fieldName; | ||
var field = aliasUsed ? resultKey : fieldName; | ||
var updatedContext = __assign({}, context, { cache: cache, query: queryFn, mutate: mutateFn }); | ||
var resolverMap = resolvers[rootValue.__typename || type]; | ||
if (resolverMap) { | ||
var resolve = resolverMap[field]; | ||
if (resolve) { | ||
return resolve(rootValue, args, updatedContext, info); | ||
} | ||
} | ||
if (normalNode && normalNode.type && normalNode.type === 'id') { | ||
normalNode = cacheData[normalNode.id]; | ||
} | ||
if (aliasedNode && aliasedNode.type && aliasedNode.type === 'id') { | ||
aliasedNode = cacheData[aliasedNode.id]; | ||
} | ||
if (normalNode !== undefined || aliasedNode !== undefined) { | ||
return aliasedNode || normalNode; | ||
} | ||
var cacheValue = cacheData['ROOT_QUERY'][field]; | ||
var result = cacheValue && cacheValue.typename | ||
? cacheData[cacheValue.id] | ||
: cacheValue; | ||
return result; | ||
}; | ||
return resolver; | ||
}; | ||
QueryManager.prototype.prepareClientExportVariables = function (document, variables, context) { | ||
if (variables === void 0) { variables = {}; } | ||
if (context === void 0) { context = {}; } | ||
return __awaiter(this, void 0, void 0, function () { | ||
var clientVariables, clientDirectiveOnlyDoc, localResult_1; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
clientVariables = {}; | ||
if (!document) return [3, 2]; | ||
clientDirectiveOnlyDoc = getDirectivesFromDocument([{ name: 'client' }], document); | ||
if (!clientDirectiveOnlyDoc) return [3, 2]; | ||
return [4, this.resolveDocumentLocally(clientDirectiveOnlyDoc, variables, context)]; | ||
case 1: | ||
localResult_1 = _a.sent(); | ||
clientDirectiveOnlyDoc.definitions | ||
.filter(function (definition) { | ||
return definition.selectionSet && definition.selectionSet.selections; | ||
}) | ||
.map(function (x) { return flattenSelections(x); }) | ||
.reduce(function (selections, selected) { return selections.concat(selected); }, []) | ||
.filter(function (selection) { | ||
return selection.directives && selection.directives.length > 0; | ||
}) | ||
.forEach(function (field) { | ||
var directiveInfo = getDirectiveInfoFromField(field, {}); | ||
if (directiveInfo && directiveInfo.export) { | ||
var value = localResult_1[field.name.value] || | ||
localResult_1[Object.keys(localResult_1)[0]][field.name.value]; | ||
if (value.json) { | ||
value = value.json; | ||
} | ||
clientVariables[directiveInfo.export.as] = value; | ||
} | ||
}); | ||
_a.label = 2; | ||
case 2: return [2, __assign({}, variables, clientVariables)]; | ||
} | ||
}); | ||
}); | ||
}; | ||
QueryManager.prototype.resolveDocumentLocally = function (clientQuery, variables, context) { | ||
if (context === void 0) { context = {}; } | ||
return __awaiter(this, void 0, void 0, function () { | ||
var localResult, resolver, updatedContext; | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: | ||
if (!clientQuery) return [3, 2]; | ||
resolver = this.prepareResolver(clientQuery, true); | ||
if (!resolver) return [3, 2]; | ||
updatedContext = this.contextCopyWithCache(context); | ||
return [4, graphql(resolver, clientQuery, {}, updatedContext, variables)]; | ||
case 1: | ||
localResult = _a.sent(); | ||
_a.label = 2; | ||
case 2: return [2, localResult]; | ||
} | ||
}); | ||
}); | ||
}; | ||
return QueryManager; | ||
@@ -882,0 +1202,0 @@ }()); |
@@ -0,5 +1,6 @@ | ||
import { FetchResult } from 'apollo-link'; | ||
import { DocumentNode, GraphQLError } from 'graphql'; | ||
import ApolloClient from '../ApolloClient'; | ||
import { QueryStoreValue } from '../data/queries'; | ||
import { NetworkStatus } from './networkStatus'; | ||
import { FetchResult } from 'apollo-link'; | ||
export declare type QueryListener = (queryStoreValue: QueryStoreValue, newData?: any) => void; | ||
@@ -38,2 +39,10 @@ export declare type OperationVariables = { | ||
}; | ||
export interface Initializers<TCacheShape> { | ||
[field: string]: (client: ApolloClient<TCacheShape>) => any; | ||
} | ||
export interface Resolvers { | ||
[key: string]: { | ||
[field: string]: (rootValue: any, args: any, context: any, info: any) => any; | ||
}; | ||
} | ||
//# sourceMappingURL=types.d.ts.map |
@@ -29,12 +29,12 @@ import { DocumentNode, ExecutionResult } from 'graphql'; | ||
} | ||
export declare type UpdateQueryFn<TData = any, TVariables = OperationVariables, TSubscriptionData = TData> = (previousQueryResult: TData, options: { | ||
export declare type UpdateQueryFn<TData = any, TVariables = OperationVariables> = (previousQueryResult: TData, options: { | ||
subscriptionData: { | ||
data: TSubscriptionData; | ||
data: TData; | ||
}; | ||
variables?: TVariables; | ||
}) => TData; | ||
export declare type SubscribeToMoreOptions<TData = any, TVariables = OperationVariables, TSubscriptionData = TData> = { | ||
export declare type SubscribeToMoreOptions<TData = any, TVariables = OperationVariables> = { | ||
document: DocumentNode; | ||
variables?: TVariables; | ||
updateQuery?: UpdateQueryFn<TData, TVariables, TSubscriptionData>; | ||
updateQuery?: UpdateQueryFn<TData, TVariables>; | ||
onError?: (error: Error) => void; | ||
@@ -41,0 +41,0 @@ }; |
import { ExecutionResult, DocumentNode } from 'graphql'; | ||
import { ApolloCache, DataProxy } from 'apollo-cache'; | ||
import { QueryStoreValue } from '../data/queries'; | ||
import { MutationQueryReducer } from '../core/types'; | ||
import { MutationQueryReducer, Initializers } from '../core/types'; | ||
import ApolloClient from '..'; | ||
export declare type QueryWithUpdater = { | ||
@@ -18,2 +19,3 @@ updater: MutationQueryReducer<Object>; | ||
private cache; | ||
private firedInitializers; | ||
constructor(initialCache: ApolloCache<TSerialized>); | ||
@@ -49,3 +51,7 @@ getCache(): ApolloCache<TSerialized>; | ||
reset(): Promise<void>; | ||
initialize(initializers: Initializers<TSerialized> | Initializers<TSerialized>[], client: ApolloClient<TSerialized>): Promise<void[]>; | ||
initializeSync(initializers: Initializers<TSerialized> | Initializers<TSerialized>[]): void; | ||
private mergeInitializers; | ||
private runInitializers; | ||
} | ||
//# sourceMappingURL=store.d.ts.map |
@@ -0,4 +1,16 @@ | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
import { getOperationName, tryFunctionOrLogError, graphQLResultHasError, } from 'apollo-utilities'; | ||
var DataStore = (function () { | ||
function DataStore(initialCache) { | ||
this.firedInitializers = []; | ||
this.cache = initialCache; | ||
@@ -135,2 +147,54 @@ } | ||
}; | ||
DataStore.prototype.initialize = function (initializers, client) { | ||
var _this = this; | ||
if (!initializers) { | ||
throw new Error('Invalid/missing initializers'); | ||
} | ||
var mergedInitializers = this.mergeInitializers(initializers); | ||
var initializerPromises = []; | ||
this.runInitializers(mergedInitializers, function (fieldName, initializer) { | ||
initializerPromises.push(Promise.resolve(initializer(client)).then(function (result) { | ||
var _a; | ||
if (result !== null) { | ||
_this.cache.writeData({ data: (_a = {}, _a[fieldName] = result, _a) }); | ||
} | ||
})); | ||
}); | ||
return Promise.all(initializerPromises); | ||
}; | ||
DataStore.prototype.initializeSync = function (initializers) { | ||
var _this = this; | ||
if (!initializers) { | ||
throw new Error('Invalid/missing initializers'); | ||
} | ||
var mergedInitializers = this.mergeInitializers(initializers); | ||
this.runInitializers(mergedInitializers, function (fieldName, initializer) { | ||
var _a; | ||
var result = initializer(_this); | ||
if (result !== null) { | ||
_this.cache.writeData({ data: (_a = {}, _a[fieldName] = result, _a) }); | ||
} | ||
}); | ||
}; | ||
DataStore.prototype.mergeInitializers = function (initializers) { | ||
var mergedInitializers = {}; | ||
if (Array.isArray(initializers)) { | ||
initializers.forEach(function (initializerGroup) { | ||
mergedInitializers = __assign({}, mergedInitializers, initializerGroup); | ||
}); | ||
} | ||
else { | ||
mergedInitializers = initializers; | ||
} | ||
return mergedInitializers; | ||
}; | ||
DataStore.prototype.runInitializers = function (initializers, runFunc) { | ||
var _this = this; | ||
Object.keys(initializers).forEach(function (fieldName) { | ||
if (_this.firedInitializers.indexOf(fieldName) < 0) { | ||
runFunc(fieldName, initializers[fieldName]); | ||
_this.firedInitializers.push(fieldName); | ||
} | ||
}); | ||
}; | ||
return DataStore; | ||
@@ -137,0 +201,0 @@ }()); |
{ | ||
"name": "apollo-client", | ||
"version": "2.4.5", | ||
"version": "2.5.0-alpha.1", | ||
"description": "A simple yet functional GraphQL client.", | ||
@@ -28,6 +28,7 @@ "main": "bundle.umd.js", | ||
"@types/zen-observable": "^0.8.0", | ||
"apollo-cache": "1.1.20", | ||
"apollo-cache": "1.2.0-alpha.1", | ||
"apollo-link": "^1.0.0", | ||
"apollo-link-dedup": "^1.0.0", | ||
"apollo-utilities": "1.0.25", | ||
"apollo-utilities": "1.1.0-alpha.1", | ||
"graphql-anywhere": "4.2.0-alpha.1", | ||
"symbol-observable": "^1.0.2", | ||
@@ -40,4 +41,4 @@ "zen-observable": "^0.8.0" | ||
"optionalDependencies": { | ||
"@types/async": "2.0.50" | ||
"@types/async": "2.0.49" | ||
} | ||
} |
@@ -1,2 +0,2 @@ | ||
export declare const version = "2.4.5"; | ||
export declare const version = "2.5.0-alpha.1"; | ||
//# sourceMappingURL=version.d.ts.map |
@@ -1,1 +0,1 @@ | ||
exports.version = "2.4.5" | ||
exports.version = "2.5.0-alpha.1" |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
565029
81
5385
10
2
+ Added@types/async@2.0.49(transitive)
+ Addedapollo-cache@1.2.0-alpha.1(transitive)
+ Addedapollo-utilities@1.1.0-alpha.1(transitive)
+ Addedfclone@1.0.11(transitive)
+ Addedgraphql-anywhere@4.2.0-alpha.1(transitive)
- Removed@types/async@2.0.50(transitive)
- Removedapollo-cache@1.1.20(transitive)
- Removedapollo-utilities@1.0.25(transitive)
Updatedapollo-cache@1.2.0-alpha.1