apollo-client
Advanced tools
Comparing version 2.5.0-alpha.1 to 2.5.0-alpha.2
import { ApolloLink, FetchResult, GraphQLRequest } from 'apollo-link'; | ||
import { ExecutionResult, DocumentNode } from 'graphql'; | ||
import { ApolloCache, DataProxy } from 'apollo-cache'; | ||
import { FragmentMatcher } from 'graphql-anywhere'; | ||
import { QueryManager } from './core/QueryManager'; | ||
@@ -16,3 +17,3 @@ import { ApolloQueryResult, OperationVariables, Initializers, Resolvers } from './core/types'; | ||
export declare type ApolloClientOptions<TCacheShape> = { | ||
link: ApolloLink; | ||
link?: ApolloLink; | ||
cache: ApolloCache<TCacheShape>; | ||
@@ -27,2 +28,5 @@ ssrForceFetchDelay?: number; | ||
typeDefs?: string | string[] | DocumentNode | DocumentNode[]; | ||
fragmentMatcher?: FragmentMatcher; | ||
name?: string; | ||
version?: string; | ||
}; | ||
@@ -42,2 +46,4 @@ export default class ApolloClient<TCacheShape> implements DataProxy { | ||
private resetStoreCallbacks; | ||
private clientAwareness; | ||
private localState; | ||
constructor(options: ApolloClientOptions<TCacheShape>); | ||
@@ -64,7 +70,9 @@ watchQuery<T, TVariables = OperationVariables>(options: WatchQueryOptions<TVariables>): ObservableQuery<T>; | ||
addResolvers(resolvers: Resolvers | Resolvers[]): void; | ||
getResolvers(): Resolvers; | ||
setResolvers(resolvers: Resolvers | Resolvers[]): void; | ||
getResolvers(): Resolvers | Resolvers[]; | ||
setTypeDefs(typeDefs: string | string[] | DocumentNode | DocumentNode[]): void; | ||
getTypeDefs(): string | string[] | DocumentNode | DocumentNode[] | undefined; | ||
setFragmentMatcher(fragmentMatcher: FragmentMatcher): void; | ||
private initProxy; | ||
} | ||
//# sourceMappingURL=ApolloClient.d.ts.map |
@@ -15,9 +15,6 @@ var __assign = (this && this.__assign) || function () { | ||
import { QueryManager } from './core/QueryManager'; | ||
import { LocalState } from './core/LocalState'; | ||
import { DataStore } from './data/store'; | ||
import { version } from './version'; | ||
var hasSuggestedDevtools = false; | ||
var supportedDirectives = new ApolloLink(function (operation, forward) { | ||
operation.query = removeConnectionDirectiveFromDocument(operation.query); | ||
return forward(operation); | ||
}); | ||
var ApolloClient = (function () { | ||
@@ -28,6 +25,22 @@ 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, initializers = options.initializers, resolvers = options.resolvers, typeDefs = options.typeDefs; | ||
this.clientAwareness = {}; | ||
var 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, fragmentMatcher = options.fragmentMatcher, clientAwarenessName = options.name, clientAwarenessVersion = options.version; | ||
var link = options.link; | ||
if (!link && (initializers || resolvers)) { | ||
link = ApolloLink.empty(); | ||
} | ||
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); | ||
@@ -63,2 +76,3 @@ this.cache = cache; | ||
if (window.navigator && | ||
window.navigator.userAgent && | ||
window.navigator.userAgent.indexOf('Chrome') > -1) { | ||
@@ -73,11 +87,16 @@ console.debug('Download the Apollo DevTools ' + | ||
this.version = version; | ||
if (initializers) { | ||
this.store.initializeSync(initializers); | ||
if (clientAwarenessName) { | ||
this.clientAwareness.name = clientAwarenessName; | ||
} | ||
if (resolvers) { | ||
this.addResolvers(resolvers); | ||
if (clientAwarenessVersion) { | ||
this.clientAwareness.version = clientAwarenessVersion; | ||
} | ||
if (typeDefs) { | ||
this.setTypeDefs(typeDefs); | ||
} | ||
this.localState = new LocalState({ | ||
cache: cache, | ||
client: this, | ||
initializers: initializers, | ||
resolvers: resolvers, | ||
typeDefs: typeDefs, | ||
fragmentMatcher: fragmentMatcher, | ||
}); | ||
} | ||
@@ -153,2 +172,4 @@ ApolloClient.prototype.watchQuery = function (options) { | ||
ssrMode: this.ssrMode, | ||
clientAwareness: this.clientAwareness, | ||
localState: this.localState, | ||
onBroadcast: function () { | ||
@@ -191,3 +212,5 @@ if (_this.devToolsHookCb) { | ||
var queryManager = this.queryManager; | ||
return Promise.resolve().then(function () { return (queryManager ? queryManager.clearStore() : Promise.resolve(null)); }); | ||
return Promise.resolve().then(function () { | ||
return queryManager ? queryManager.clearStore() : Promise.resolve(null); | ||
}); | ||
}; | ||
@@ -213,16 +236,22 @@ ApolloClient.prototype.onResetStore = function (cb) { | ||
ApolloClient.prototype.runInitializers = function (initializers) { | ||
this.store.initialize(initializers, this); | ||
this.localState.runInitializers(initializers); | ||
}; | ||
ApolloClient.prototype.addResolvers = function (resolvers) { | ||
this.initQueryManager().addResolvers(resolvers); | ||
this.localState.addResolvers(resolvers); | ||
}; | ||
ApolloClient.prototype.setResolvers = function (resolvers) { | ||
this.localState.setResolvers(resolvers); | ||
}; | ||
ApolloClient.prototype.getResolvers = function () { | ||
return this.initQueryManager().getResolvers(); | ||
return this.localState.getResolvers(); | ||
}; | ||
ApolloClient.prototype.setTypeDefs = function (typeDefs) { | ||
this.initQueryManager().setTypeDefs(typeDefs); | ||
this.localState.setTypeDefs(typeDefs); | ||
}; | ||
ApolloClient.prototype.getTypeDefs = function () { | ||
return this.queryManager ? this.queryManager.getTypeDefs() : undefined; | ||
return this.localState.getTypeDefs(); | ||
}; | ||
ApolloClient.prototype.setFragmentMatcher = function (fragmentMatcher) { | ||
this.localState.setFragmentMatcher(fragmentMatcher); | ||
}; | ||
ApolloClient.prototype.initProxy = function () { | ||
@@ -229,0 +258,0 @@ if (!this.proxy) { |
@@ -39,2 +39,3 @@ import { GraphQLError } from 'graphql'; | ||
private lastResult; | ||
private lastResultSnapshot; | ||
private lastError; | ||
@@ -48,2 +49,3 @@ constructor({ scheduler, options, shouldSubscribe, }: { | ||
currentResult(): ApolloCurrentResult<TData>; | ||
isDifferentFromLastResult(newResult: ApolloQueryResult<TData>): boolean; | ||
getLastResult(): ApolloQueryResult<TData>; | ||
@@ -54,3 +56,3 @@ getLastError(): ApolloError; | ||
fetchMore<K extends keyof TVariables>(fetchMoreOptions: FetchMoreQueryOptions<TVariables, K> & FetchMoreOptions<TData, TVariables>): Promise<ApolloQueryResult<TData>>; | ||
subscribeToMore(options: SubscribeToMoreOptions<TData, TVariables>): () => void; | ||
subscribeToMore<TSubscriptionData = TData>(options: SubscribeToMoreOptions<TData, TVariables, TSubscriptionData>): () => void; | ||
setOptions(opts: ModifiableWatchQueryOptions): Promise<ApolloQueryResult<TData>>; | ||
@@ -57,0 +59,0 @@ setVariables(variables: TVariables, tryFetch?: boolean, fetchResults?: boolean): Promise<ApolloQueryResult<TData>>; |
@@ -25,3 +25,3 @@ var __extends = (this && this.__extends) || (function () { | ||
}; | ||
import { isEqual, tryFunctionOrLogError } from 'apollo-utilities'; | ||
import { isEqual, tryFunctionOrLogError, cloneDeep } from 'apollo-utilities'; | ||
import { NetworkStatus, isNetworkRequestInFlight } from './networkStatus'; | ||
@@ -126,7 +126,15 @@ import { Observable } from '../util/Observable'; | ||
if (!partial) { | ||
var stale = false; | ||
this.lastResult = __assign({}, result, { stale: stale }); | ||
this.lastResult = __assign({}, result, { stale: false }); | ||
this.lastResultSnapshot = cloneDeep(this.lastResult); | ||
} | ||
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 () { | ||
@@ -140,2 +148,3 @@ return this.lastResult; | ||
delete this.lastResult; | ||
delete this.lastResultSnapshot; | ||
delete this.lastError; | ||
@@ -334,2 +343,3 @@ this.isTornDown = false; | ||
_this.lastResult = result; | ||
_this.lastResultSnapshot = cloneDeep(result); | ||
_this.observers.forEach(function (obs) { return obs.next && obs.next(result); }); | ||
@@ -336,0 +346,0 @@ }, |
@@ -11,3 +11,4 @@ import { ApolloLink, FetchResult } from 'apollo-link'; | ||
import { ObservableQuery } from './ObservableQuery'; | ||
import { QueryListener, ApolloQueryResult, FetchType, OperationVariables, Resolvers } from './types'; | ||
import { QueryListener, ApolloQueryResult, FetchType, OperationVariables } from './types'; | ||
import { LocalState } from './LocalState'; | ||
export interface QueryInfo { | ||
@@ -35,2 +36,4 @@ listeners: QueryListener[]; | ||
private queryDeduplication; | ||
private clientAwareness; | ||
private localState; | ||
private onBroadcast; | ||
@@ -41,5 +44,3 @@ private idCounter; | ||
private queryIdsByName; | ||
private resolvers; | ||
private typeDefs; | ||
constructor({ link, queryDeduplication, store, onBroadcast, ssrMode, }: { | ||
constructor({ link, queryDeduplication, store, onBroadcast, ssrMode, clientAwareness, localState, }: { | ||
link: ApolloLink; | ||
@@ -50,2 +51,4 @@ queryDeduplication?: boolean; | ||
ssrMode?: boolean; | ||
clientAwareness?: Record<string, string>; | ||
localState?: LocalState<TStore>; | ||
}); | ||
@@ -82,6 +85,3 @@ mutate<T>({ mutation, variables, optimisticResponse, updateQueries: updateQueriesByName, refetchQueries, awaitRefetchQueries, update: updateWithProxyFn, errorPolicy, fetchPolicy, context, }: MutationOptions): Promise<FetchResult<T>>; | ||
broadcastQueries(): void; | ||
addResolvers(resolvers: Resolvers | Resolvers[]): void; | ||
getResolvers(): Resolvers; | ||
setTypeDefs(typeDefs: string | string[] | DocumentNode | DocumentNode[]): void; | ||
getTypeDefs(): string | string[] | DocumentNode | DocumentNode[]; | ||
getLocalState(): LocalState<TStore>; | ||
private getObservableQueryPromises; | ||
@@ -95,7 +95,4 @@ private fetchRequest; | ||
private buildOperationForLink; | ||
private contextCopyWithCache; | ||
private prepareResolver; | ||
private prepareClientExportVariables; | ||
private resolveDocumentLocally; | ||
private prepareContext; | ||
} | ||
//# sourceMappingURL=QueryManager.d.ts.map |
@@ -48,11 +48,8 @@ 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, getMainDefinition, isProduction, hasDirectives, mergeDeep, getDirectivesFromDocument, getDirectiveInfoFromField, flattenSelections, } from 'apollo-utilities'; | ||
import { assign, getDefaultValues, getMutationDefinition, getOperationDefinition, getOperationName, getQueryDefinition, isProduction, hasDirectives, graphQLResultHasError, } 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'; | ||
@@ -63,17 +60,9 @@ import { QueryStore } from '../data/queries'; | ||
import { FetchType, } from './types'; | ||
import { graphQLResultHasError } from 'apollo-utilities'; | ||
var defaultQueryInfo = { | ||
listeners: [], | ||
invalidated: false, | ||
document: null, | ||
newData: null, | ||
lastRequestId: null, | ||
observableQuery: null, | ||
subscriptions: [], | ||
}; | ||
import { LocalState } from './LocalState'; | ||
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; | ||
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; | ||
this.mutationStore = new MutationStore(); | ||
this.queryStore = new QueryStore(); | ||
this.clientAwareness = {}; | ||
this.idCounter = 1; | ||
@@ -83,3 +72,2 @@ this.queries = new Map(); | ||
this.queryIdsByName = {}; | ||
this.resolvers = {}; | ||
this.link = link; | ||
@@ -90,44 +78,140 @@ this.deduplicator = ApolloLink.from([new Deduplicator(), link]); | ||
this.onBroadcast = onBroadcast; | ||
this.clientAwareness = clientAwareness; | ||
this.scheduler = new QueryScheduler({ queryManager: this, ssrMode: ssrMode }); | ||
this.localState = localState || new LocalState({ cache: store.getCache() }); | ||
} | ||
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; | ||
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), | ||
}; | ||
}); | ||
}); | ||
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 ret; | ||
}; | ||
var updatedVariables = this.localState.addExportedVariables(mutation, variables, context); | ||
this.mutationStore.initMutation(mutationId, mutationString, updatedVariables); | ||
this.dataStore.markMutationInit({ | ||
mutationId: mutationId, | ||
document: mutation, | ||
variables: updatedVariables || {}, | ||
updateQueries: generateUpdateQueriesInfo(), | ||
update: updateWithProxyFn, | ||
optimisticResponse: optimisticResponse, | ||
}); | ||
this.broadcastQueries(); | ||
return 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); | ||
} | ||
return ret; | ||
}; | ||
return [4, this.prepareClientExportVariables(mutation, variables, context)]; | ||
case 1: | ||
updatedVariables = _f.sent(); | ||
this.mutationStore.initMutation(mutationId, mutationString, updatedVariables); | ||
this.dataStore.markMutationInit({ | ||
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 = _this.localState.clientQuery(operation.query); | ||
var serverQuery = _this.localState.serverQuery(operation.query); | ||
if (serverQuery) { | ||
operation.query = serverQuery; | ||
} | ||
var obs = serverQuery | ||
? execute(_this.link, operation) | ||
: Observable.of({ | ||
data: {}, | ||
}); | ||
var self = _this; | ||
obs.subscribe({ | ||
next: function (result) { | ||
if (graphQLResultHasError(result) && errorPolicy === 'none') { | ||
error = new ApolloError({ | ||
graphQLErrors: result.errors, | ||
}); | ||
return; | ||
} | ||
self.mutationStore.markMutationResult(mutationId); | ||
var updatedResult = result; | ||
var context = operation.context, variables = operation.variables; | ||
updatedResult.data = self.localState.runResolvers({ | ||
query: clientQuery, | ||
remoteResult: result.data, | ||
context: context, | ||
variables: variables, | ||
onError: function (error) { | ||
reject(error); | ||
}, | ||
}); | ||
if (fetchPolicy !== 'no-cache') { | ||
self.dataStore.markMutationResult({ | ||
mutationId: mutationId, | ||
result: updatedResult, | ||
document: mutation, | ||
@@ -137,150 +221,21 @@ variables: updatedVariables || {}, | ||
update: updateWithProxyFn, | ||
optimisticResponse: optimisticResponse, | ||
}); | ||
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; | ||
}, | ||
}); | ||
})]; | ||
} | ||
} | ||
storeResult = updatedResult; | ||
}, | ||
error: function (err) { | ||
self.mutationStore.markMutationError(mutationId, err); | ||
self.dataStore.markMutationComplete({ | ||
mutationId: mutationId, | ||
optimisticResponse: optimisticResponse, | ||
}); | ||
self.broadcastQueries(); | ||
self.setQuery(mutationId, function () { return ({ document: undefined }); }); | ||
reject(new ApolloError({ | ||
networkError: err, | ||
})); | ||
}, | ||
complete: function () { | ||
completeMutation().then(resolve, reject); | ||
}, | ||
}); | ||
@@ -290,90 +245,81 @@ }); | ||
QueryManager.prototype.fetchQuery = function (queryId, options, fetchType, fetchMoreForQueryId) { | ||
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 })]; | ||
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, _d = options.context, context = _d === void 0 ? {} : _d; | ||
var cache = this.dataStore.getCache(); | ||
var query = cache.transformDocument(options.query); | ||
var updatedVariables = this.localState.addExportedVariables(query, variables, context); | ||
var updatedOptions = __assign({}, options, { variables: updatedVariables }); | ||
var storeResult; | ||
var needToFetch = fetchPolicy === 'network-only' || fetchPolicy === 'no-cache'; | ||
if (fetchType !== FetchType.refetch && | ||
fetchPolicy !== 'network-only' && | ||
fetchPolicy !== 'no-cache') { | ||
var _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; | ||
} | ||
var shouldFetch = needToFetch && fetchPolicy !== 'cache-only' && fetchPolicy !== 'standby'; | ||
if (hasDirectives(['live'], query)) | ||
shouldFetch = true; | ||
var requestId = this.generateRequestId(); | ||
var 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(); | ||
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: 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 networkResult; | ||
} | ||
else { | ||
networkResult.catch(function () { }); | ||
} | ||
} | ||
return Promise.resolve({ data: storeResult }); | ||
}; | ||
@@ -493,8 +439,5 @@ QueryManager.prototype.queryListenerForObserver = function (queryId, options, observer) { | ||
if (observer.next) { | ||
var isDifferentResult = !(lastResult && | ||
resultFromStore && | ||
lastResult.networkStatus === resultFromStore.networkStatus && | ||
lastResult.stale === resultFromStore.stale && | ||
lastResult.data === resultFromStore.data); | ||
if (isDifferentResult || previouslyHadError) { | ||
if (previouslyHadError || | ||
!observableQuery || | ||
observableQuery.isDifferentFromLastResult(resultFromStore)) { | ||
try { | ||
@@ -664,2 +607,3 @@ observer.next(resultFromStore); | ||
var reset = this.dataStore.reset(); | ||
this.localState.resetInitializers(); | ||
return reset; | ||
@@ -691,53 +635,32 @@ }; | ||
var variables = assign({}, getDefaultValues(getOperationDefinition(query)), options.variables); | ||
var updatedVariables = variables; | ||
var sub; | ||
var observers = []; | ||
var clientQuery = this.localState.clientQuery(transformedDoc); | ||
return new Observable(function (observer) { | ||
observers.push(observer); | ||
if (observers.length === 1) { | ||
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]; | ||
var handler = { | ||
next: function (result) { | ||
var updatedResult = result; | ||
updatedResult.data = _this.localState.runResolvers({ | ||
query: clientQuery, | ||
remoteResult: result.data, | ||
context: {}, | ||
variables: variables, | ||
}); | ||
if (isCacheEnabled) { | ||
_this.dataStore.markSubscriptionResult(updatedResult, transformedDoc, updatedVariables_1); | ||
_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); | ||
} | ||
}); | ||
}); }, | ||
}, | ||
error: function (error) { | ||
@@ -751,20 +674,11 @@ observers.forEach(function (obs) { | ||
}; | ||
(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]; | ||
} | ||
}); | ||
}); })(); | ||
var updatedVariables_1 = _this.localState.addExportedVariables(transformedDoc, variables); | ||
var serverQuery = _this.localState.serverQuery(transformedDoc); | ||
if (serverQuery) { | ||
var operation = _this.buildOperationForLink(serverQuery, updatedVariables_1); | ||
sub = execute(_this.link, operation).subscribe(handler); | ||
} | ||
else { | ||
sub = Observable.of({ data: {} }).subscribe(handler); | ||
} | ||
} | ||
@@ -793,3 +707,3 @@ return function () { | ||
var newData = this.getQuery(observableQuery.queryId).newData; | ||
if (newData) { | ||
if (newData && newData.complete) { | ||
return { data: newData.result, partial: false }; | ||
@@ -845,22 +759,5 @@ } | ||
}; | ||
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.getLocalState = function () { | ||
return this.localState; | ||
}; | ||
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) { | ||
@@ -888,98 +785,74 @@ var _this = this; | ||
var variables = options.variables, context = options.context, _b = options.errorPolicy, errorPolicy = _b === void 0 ? 'none' : _b, fetchPolicy = options.fetchPolicy; | ||
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; | ||
var errorsFromStore; | ||
return new Promise(function (resolve, reject) { | ||
var obs; | ||
var updatedContext = {}; | ||
var clientQuery = _this.localState.clientQuery(document); | ||
var serverQuery = _this.localState.serverQuery(document); | ||
if (serverQuery) { | ||
var operation = _this.buildOperationForLink(serverQuery, variables, __assign({}, context, { forceFetch: !_this.queryDeduplication })); | ||
updatedContext = operation.context; | ||
obs = execute(_this.deduplicator, operation); | ||
} | ||
else { | ||
updatedContext = _this.prepareContext(context); | ||
obs = Observable.of({ data: {} }); | ||
} | ||
_this.addFetchQueryPromise(requestId, resolve, reject); | ||
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]; | ||
next: function (result) { | ||
var updatedResult = result; | ||
var lastRequestId = _this.getQuery(queryId).lastRequestId; | ||
if (requestId >= (lastRequestId || 1)) { | ||
updatedResult.data = _this.localState.runResolvers({ | ||
query: clientQuery, | ||
remoteResult: result.data, | ||
context: updatedContext, | ||
variables: variables, | ||
onError: function (error) { | ||
reject(error); | ||
}, | ||
}); | ||
if (fetchPolicy !== 'no-cache') { | ||
try { | ||
_this.dataStore.markQueryResult(updatedResult, document, variables, fetchMoreForQueryId, errorPolicy === 'ignore' || errorPolicy === 'all'); | ||
} | ||
catch (e) { | ||
reject(e); | ||
return; | ||
} | ||
} | ||
}); | ||
}); }, | ||
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(); | ||
} | ||
if (updatedResult.errors && errorPolicy === 'none') { | ||
reject(new ApolloError({ | ||
graphQLErrors: updatedResult.errors, | ||
})); | ||
return; | ||
} | ||
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) { } | ||
} | ||
}, | ||
error: function (error) { | ||
@@ -996,19 +869,16 @@ _this.removeFetchQueryPromise(requestId); | ||
complete: function () { | ||
if (!handlingNext) { | ||
_this.removeFetchQueryPromise(requestId); | ||
_this.setQuery(queryId, function (_a) { | ||
var subscriptions = _a.subscriptions; | ||
return ({ | ||
subscriptions: subscriptions.filter(function (x) { return x !== subscription; }), | ||
}); | ||
_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, | ||
}); | ||
} | ||
complete = true; | ||
}); | ||
resolve({ | ||
data: resultFromStore, | ||
errors: errorsFromStore, | ||
loading: false, | ||
networkStatus: NetworkStatus.ready, | ||
stale: false, | ||
}); | ||
}, | ||
@@ -1041,3 +911,11 @@ }; | ||
QueryManager.prototype.getQuery = function (queryId) { | ||
return this.queries.get(queryId) || __assign({}, defaultQueryInfo); | ||
return (this.queries.get(queryId) || { | ||
listeners: [], | ||
invalidated: false, | ||
document: null, | ||
newData: null, | ||
lastRequestId: null, | ||
observableQuery: null, | ||
subscriptions: [], | ||
}); | ||
}; | ||
@@ -1064,138 +942,10 @@ QueryManager.prototype.setQuery = function (queryId, updater) { | ||
operationName: getOperationName(document) || undefined, | ||
context: this.contextCopyWithCache(extraContext), | ||
context: this.prepareContext(extraContext), | ||
}; | ||
}; | ||
QueryManager.prototype.contextCopyWithCache = function (context) { | ||
QueryManager.prototype.prepareContext = 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.'); | ||
} | ||
} }); | ||
var newContext = this.localState.prepareContext(context); | ||
return __assign({}, newContext, { clientAwareness: this.clientAwareness }); | ||
}; | ||
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; | ||
@@ -1202,0 +952,0 @@ }()); |
@@ -44,5 +44,5 @@ import { FetchResult } from 'apollo-link'; | ||
[key: string]: { | ||
[field: string]: (rootValue: any, args: any, context: any, info: any) => any; | ||
[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> = (previousQueryResult: TData, options: { | ||
export declare type UpdateQueryFn<TData = any, TVariables = OperationVariables, TSubscriptionData = TData> = (previousQueryResult: TData, options: { | ||
subscriptionData: { | ||
data: TData; | ||
data: TSubscriptionData; | ||
}; | ||
variables?: TVariables; | ||
}) => TData; | ||
export declare type SubscribeToMoreOptions<TData = any, TVariables = OperationVariables> = { | ||
export declare type SubscribeToMoreOptions<TData = any, TVariables = OperationVariables, TSubscriptionData = TData> = { | ||
document: DocumentNode; | ||
variables?: TVariables; | ||
updateQuery?: UpdateQueryFn<TData, TVariables>; | ||
updateQuery?: UpdateQueryFn<TData, TVariables, TSubscriptionData>; | ||
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, Initializers } from '../core/types'; | ||
import ApolloClient from '..'; | ||
import { MutationQueryReducer } from '../core/types'; | ||
export declare type QueryWithUpdater = { | ||
@@ -19,3 +18,2 @@ updater: MutationQueryReducer<Object>; | ||
private cache; | ||
private firedInitializers; | ||
constructor(initialCache: ApolloCache<TSerialized>); | ||
@@ -51,7 +49,3 @@ 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 |
@@ -1,16 +0,4 @@ | ||
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; | ||
@@ -147,54 +135,2 @@ } | ||
}; | ||
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; | ||
@@ -201,0 +137,0 @@ }()); |
{ | ||
"name": "apollo-client", | ||
"version": "2.5.0-alpha.1", | ||
"version": "2.5.0-alpha.2", | ||
"description": "A simple yet functional GraphQL client.", | ||
@@ -28,7 +28,7 @@ "main": "bundle.umd.js", | ||
"@types/zen-observable": "^0.8.0", | ||
"apollo-cache": "1.2.0-alpha.1", | ||
"apollo-cache": "1.2.0-alpha.2", | ||
"apollo-link": "^1.0.0", | ||
"apollo-link-dedup": "^1.0.0", | ||
"apollo-utilities": "1.1.0-alpha.1", | ||
"graphql-anywhere": "4.2.0-alpha.1", | ||
"apollo-utilities": "1.1.0-alpha.2", | ||
"graphql-anywhere": "4.2.0-alpha.2", | ||
"symbol-observable": "^1.0.2", | ||
@@ -39,6 +39,3 @@ "zen-observable": "^0.8.0" | ||
"graphql": "^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0" | ||
}, | ||
"optionalDependencies": { | ||
"@types/async": "2.0.49" | ||
} | ||
} |
@@ -123,1 +123,6 @@ # [Apollo Client](https://www.apollographql.com/client/) [![npm version](https://badge.fury.io/js/apollo-client.svg)](https://badge.fury.io/js/apollo-client) [![Get on Slack](https://img.shields.io/badge/slack-join-orange.svg)](http://www.apollostack.com/#slack) [![Open Source Helpers](https://www.codetriage.com/apollographql/apollo-client/badges/users.svg)](https://www.codetriage.com/apollographql/apollo-client) | ||
1. [Long conversation about different client options, before this repo existed](https://github.com/apollostack/apollo/issues/1) | ||
## Maintainers | ||
- [@benjamn](https://github.com/benjamn) (Apollo) | ||
- [@hwillson](https://github.com/hwillson) (Apollo) |
@@ -1,2 +0,2 @@ | ||
export declare const version = "2.5.0-alpha.1"; | ||
export declare const version = "2.5.0-alpha.2"; | ||
//# sourceMappingURL=version.d.ts.map |
@@ -1,1 +0,1 @@ | ||
exports.version = "2.5.0-alpha.1" | ||
exports.version = "2.5.0-alpha.2" |
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
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
9
5436
128
561200
+ Addedapollo-cache@1.2.0-alpha.2(transitive)
+ Addedapollo-utilities@1.1.0-alpha.2(transitive)
+ Addedgraphql-anywhere@4.2.0-alpha.2(transitive)
- Removed@types/async@2.0.49(transitive)
- Removedapollo-cache@1.2.0-alpha.1(transitive)
- Removedapollo-utilities@1.1.0-alpha.1(transitive)
- Removedfclone@1.0.11(transitive)
- Removedgraphql-anywhere@4.2.0-alpha.1(transitive)
Updatedapollo-cache@1.2.0-alpha.2