@apollo/react-hooks
Advanced tools
Comparing version 0.1.0-beta.7 to 0.1.0-beta.8
@@ -13,3 +13,3 @@ import { ApolloContextValue, OperationVariables, ExecutionResult, MutationFunctionOptions, MutationResult } from '@apollo/react-common'; | ||
result: MutationResult<TData>; | ||
setResult: any; | ||
setResult: (result: MutationResult<TData>) => any; | ||
}); | ||
@@ -16,0 +16,0 @@ execute(result: MutationResult<TData>): [(options?: MutationFunctionOptions<TData, TVariables> | undefined) => Promise<void | ExecutionResult<TData>>, MutationResult<TData>]; |
@@ -19,3 +19,3 @@ import * as tslib_1 from "tslib"; | ||
var _this = this; | ||
this.verifyDocumentType(this.options.mutation, DocumentType.Mutation); | ||
this.verifyDocumentType(this.getOptions().mutation, DocumentType.Mutation); | ||
var runMutation = function (options) { return _this.runMutation(options); }; | ||
@@ -42,3 +42,3 @@ return [runMutation, result]; | ||
_this.onMutationError(error, mutationId); | ||
if (!_this.options.onError) | ||
if (!_this.getOptions().onError) | ||
throw error; | ||
@@ -48,15 +48,12 @@ }); | ||
MutationData.prototype.mutate = function (mutationFunctionOptions) { | ||
var _a = this.options, mutation = _a.mutation, variables = _a.variables, optimisticResponse = _a.optimisticResponse, update = _a.update, _b = _a.context, mutationContext = _b === void 0 ? {} : _b, _c = _a.awaitRefetchQueries, awaitRefetchQueries = _c === void 0 ? false : _c, fetchPolicy = _a.fetchPolicy; | ||
var _a = this.getOptions(), mutation = _a.mutation, variables = _a.variables, optimisticResponse = _a.optimisticResponse, update = _a.update, _b = _a.context, mutationContext = _b === void 0 ? {} : _b, _c = _a.awaitRefetchQueries, awaitRefetchQueries = _c === void 0 ? false : _c, fetchPolicy = _a.fetchPolicy; | ||
var mutateOptions = tslib_1.__assign({}, mutationFunctionOptions); | ||
var refetchQueries = mutateOptions.refetchQueries || this.options.refetchQueries; | ||
var mutateVariables = Object.assign({}, variables, mutateOptions.variables); | ||
delete mutateOptions.variables; | ||
return this.refreshClient().client.mutate(tslib_1.__assign({ mutation: mutation, | ||
optimisticResponse: optimisticResponse, | ||
refetchQueries: refetchQueries, | ||
awaitRefetchQueries: awaitRefetchQueries, | ||
optimisticResponse: optimisticResponse, refetchQueries: mutateOptions.refetchQueries || this.getOptions().refetchQueries, awaitRefetchQueries: awaitRefetchQueries, | ||
update: update, context: mutationContext, fetchPolicy: fetchPolicy, variables: mutateVariables }, mutateOptions)); | ||
}; | ||
MutationData.prototype.onMutationStart = function () { | ||
if (!this.result.loading && !this.options.ignoreResults) { | ||
if (!this.result.loading && !this.getOptions().ignoreResults) { | ||
this.updateResult({ | ||
@@ -71,3 +68,3 @@ loading: true, | ||
MutationData.prototype.onMutationCompleted = function (response, mutationId) { | ||
var _a = this.options, onCompleted = _a.onCompleted, ignoreResults = _a.ignoreResults; | ||
var _a = this.getOptions(), onCompleted = _a.onCompleted, ignoreResults = _a.ignoreResults; | ||
var data = response.data, errors = response.errors; | ||
@@ -91,4 +88,3 @@ var error = errors && errors.length > 0 | ||
MutationData.prototype.onMutationError = function (error, mutationId) { | ||
var onError = this.options.onError; | ||
var callOnError = function () { return (onError ? onError(error) : null); }; | ||
var onError = this.getOptions().onError; | ||
if (this.isMostRecentMutation(mutationId)) { | ||
@@ -102,7 +98,8 @@ this.updateResult({ | ||
} | ||
callOnError(); | ||
if (onError) { | ||
onError(error); | ||
} | ||
}; | ||
MutationData.prototype.generateNewMutationId = function () { | ||
this.mostRecentMutationId += 1; | ||
return this.mostRecentMutationId; | ||
return ++this.mostRecentMutationId; | ||
}; | ||
@@ -109,0 +106,0 @@ MutationData.prototype.isMostRecentMutation = function (mutationId) { |
@@ -6,13 +6,10 @@ import { ApolloClient } from 'apollo-client'; | ||
export declare abstract class OperationData<TOptions = any> { | ||
private _isMounted; | ||
private _options; | ||
private _previousOptions; | ||
private _context; | ||
private _client; | ||
constructor(options?: CommonOptions<TOptions>, context?: ApolloContextValue); | ||
isMounted: boolean; | ||
options: CommonOptions<TOptions>; | ||
previousOptions: CommonOptions<TOptions>; | ||
context: ApolloContextValue; | ||
client: ApolloClient<object> | undefined; | ||
private options; | ||
constructor(options?: CommonOptions<TOptions>, context?: ApolloContextValue); | ||
getOptions(): CommonOptions<TOptions>; | ||
setOptions(newOptions: CommonOptions<TOptions>): void; | ||
abstract execute(...args: any): any; | ||
@@ -19,0 +16,0 @@ abstract afterExecute(...args: any): () => void; |
@@ -6,62 +6,18 @@ import { isEqual } from 'apollo-utilities'; | ||
function OperationData(options, context) { | ||
this._isMounted = true; | ||
this._options = {}; | ||
this._previousOptions = {}; | ||
this._context = {}; | ||
this._options = options || {}; | ||
this._context = context || {}; | ||
this.isMounted = true; | ||
this.previousOptions = {}; | ||
this.context = {}; | ||
this.options = {}; | ||
this.options = options || {}; | ||
this.context = context || {}; | ||
} | ||
Object.defineProperty(OperationData.prototype, "isMounted", { | ||
get: function () { | ||
return this._isMounted; | ||
}, | ||
set: function (mounted) { | ||
this._isMounted = mounted; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(OperationData.prototype, "options", { | ||
get: function () { | ||
return this._options; | ||
}, | ||
set: function (newOptions) { | ||
if (!isEqual(this.options, newOptions)) { | ||
this.previousOptions = this.options; | ||
} | ||
this._options = newOptions; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(OperationData.prototype, "previousOptions", { | ||
get: function () { | ||
return this._previousOptions; | ||
}, | ||
set: function (newOptions) { | ||
this._previousOptions = newOptions; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(OperationData.prototype, "context", { | ||
get: function () { | ||
return this._context; | ||
}, | ||
set: function (newContext) { | ||
this._context = newContext; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(OperationData.prototype, "client", { | ||
get: function () { | ||
return this._client; | ||
}, | ||
set: function (newClient) { | ||
this._client = newClient; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
OperationData.prototype.getOptions = function () { | ||
return this.options; | ||
}; | ||
OperationData.prototype.setOptions = function (newOptions) { | ||
if (!isEqual(this.options, newOptions)) { | ||
this.previousOptions = this.options; | ||
} | ||
this.options = newOptions; | ||
}; | ||
OperationData.prototype.unmount = function () { | ||
@@ -68,0 +24,0 @@ this.isMounted = false; |
@@ -19,3 +19,3 @@ import * as tslib_1 from "tslib"; | ||
this.refreshClient(); | ||
var _a = this.options, skip = _a.skip, query = _a.query; | ||
var _a = this.getOptions(), skip = _a.skip, query = _a.query; | ||
if (skip || query !== this.previousData.query) { | ||
@@ -37,5 +37,5 @@ this.removeQuerySubscription(); | ||
QueryData.prototype.fetchData = function () { | ||
if (this.options.skip) | ||
if (this.getOptions().skip) | ||
return false; | ||
var _a = this.options, children = _a.children, ssr = _a.ssr, displayName = _a.displayName, skip = _a.skip, onCompleted = _a.onCompleted, onError = _a.onError, partialRefetch = _a.partialRefetch, opts = tslib_1.__rest(_a, ["children", "ssr", "displayName", "skip", "onCompleted", "onError", "partialRefetch"]); | ||
var _a = this.getOptions(), children = _a.children, ssr = _a.ssr, displayName = _a.displayName, skip = _a.skip, onCompleted = _a.onCompleted, onError = _a.onError, partialRefetch = _a.partialRefetch, opts = tslib_1.__rest(_a, ["children", "ssr", "displayName", "skip", "onCompleted", "onError", "partialRefetch"]); | ||
var fetchPolicy = opts.fetchPolicy; | ||
@@ -49,3 +49,3 @@ if (ssr === false) | ||
if (this.context && this.context.renderPromises) { | ||
this.context.renderPromises.registerSSRObservable(obs, this.options); | ||
this.context.renderPromises.registerSSRObservable(obs, this.getOptions()); | ||
} | ||
@@ -71,8 +71,8 @@ var result = this.currentObservable.query.getCurrentResult(); | ||
QueryData.prototype.prepareObservableQueryOptions = function () { | ||
this.verifyDocumentType(this.options.query, DocumentType.Query); | ||
var displayName = this.options.displayName || 'Query'; | ||
return tslib_1.__assign({}, this.options, { displayName: displayName, context: this.options.context || {}, metadata: { reactComponent: { displayName: displayName } } }); | ||
this.verifyDocumentType(this.getOptions().query, DocumentType.Query); | ||
var displayName = this.getOptions().displayName || 'Query'; | ||
return tslib_1.__assign({}, this.getOptions(), { displayName: displayName, context: this.getOptions().context || {}, metadata: { reactComponent: { displayName: displayName } } }); | ||
}; | ||
QueryData.prototype.observableQueryFields = function (observable) { | ||
var fields = { | ||
return { | ||
variables: observable.variables, | ||
@@ -86,7 +86,6 @@ refetch: observable.refetch.bind(observable), | ||
}; | ||
return fields; | ||
}; | ||
QueryData.prototype.initializeObservableQuery = function () { | ||
if (this.context && this.context.renderPromises) { | ||
this.currentObservable.query = this.context.renderPromises.getSSRObservable(this.options); | ||
this.currentObservable.query = this.context.renderPromises.getSSRObservable(this.getOptions()); | ||
} | ||
@@ -108,3 +107,3 @@ if (!this.currentObservable.query) { | ||
.query.setOptions(newObservableQueryOptions) | ||
.catch(function () { return null; }); | ||
.catch(function () { }); | ||
} | ||
@@ -155,3 +154,3 @@ }; | ||
Object.assign(result, this.observableQueryFields(this.currentObservable.query)); | ||
if (this.options.skip) { | ||
if (this.getOptions().skip) { | ||
result = tslib_1.__assign({}, result, { data: undefined, error: undefined, loading: false }); | ||
@@ -182,3 +181,3 @@ } | ||
var fetchPolicy = this.currentObservable.query.options.fetchPolicy; | ||
var partialRefetch = this.options.partialRefetch; | ||
var partialRefetch = this.getOptions().partialRefetch; | ||
if (partialRefetch && | ||
@@ -207,7 +206,7 @@ Object.keys(data).length === 0 && | ||
if (!loading) { | ||
var _b = this.options, query = _b.query, variables = _b.variables, onCompleted = _b.onCompleted, onError = _b.onError; | ||
var _b = this.getOptions(), query = _b.query, variables = _b.variables, onCompleted = _b.onCompleted, onError = _b.onError; | ||
if (this.previousOptions && | ||
!this.previousData.loading && | ||
isEqual(this.previousOptions.query, query) && | ||
isEqual(this.previousOptions.variables, variables) && | ||
!this.previousData.loading) { | ||
isEqual(this.previousOptions.variables, variables)) { | ||
return; | ||
@@ -214,0 +213,0 @@ } |
@@ -19,5 +19,5 @@ import * as tslib_1 from "tslib"; | ||
} | ||
var shouldResubscribe = this.options.shouldResubscribe; | ||
var shouldResubscribe = this.getOptions().shouldResubscribe; | ||
if (typeof shouldResubscribe === 'function') { | ||
shouldResubscribe = !!shouldResubscribe(this.options); | ||
shouldResubscribe = !!shouldResubscribe(this.getOptions()); | ||
} | ||
@@ -27,4 +27,4 @@ if (shouldResubscribe !== false && | ||
Object.keys(this.previousOptions).length > 0 && | ||
(!isEqual(this.previousOptions.variables, this.options.variables) || | ||
this.previousOptions.subscription !== this.options.subscription)) { | ||
(this.previousOptions.subscription !== this.getOptions().subscription || | ||
!isEqual(this.previousOptions.variables, this.getOptions().variables))) { | ||
this.endSubscription(); | ||
@@ -34,6 +34,6 @@ delete this.currentObservable.query; | ||
} | ||
this.initialize(this.options); | ||
this.initialize(this.getOptions()); | ||
this.startSubscription(); | ||
this.previousOptions = this.options; | ||
return tslib_1.__assign({}, currentResult, { variables: this.options.variables }); | ||
this.previousOptions = this.getOptions(); | ||
return tslib_1.__assign({}, currentResult, { variables: this.getOptions().variables }); | ||
}; | ||
@@ -79,3 +79,3 @@ SubscriptionData.prototype.afterExecute = function () { | ||
SubscriptionData.prototype.updateCurrentData = function (result) { | ||
var onSubscriptionData = this.options.onSubscriptionData; | ||
var onSubscriptionData = this.getOptions().onSubscriptionData; | ||
if (onSubscriptionData) { | ||
@@ -100,3 +100,3 @@ onSubscriptionData({ | ||
SubscriptionData.prototype.completeSubscription = function () { | ||
var onSubscriptionComplete = this.options.onSubscriptionComplete; | ||
var onSubscriptionComplete = this.getOptions().onSubscriptionComplete; | ||
if (onSubscriptionComplete) | ||
@@ -103,0 +103,0 @@ onSubscriptionComplete(); |
@@ -1,787 +0,889 @@ | ||
'use strict'; | ||
exports.__esModule = true; | ||
exports.getDataFromTree = getDataFromTree; | ||
exports.getMarkupFromTree = getMarkupFromTree; | ||
exports.renderToStringWithData = renderToStringWithData; | ||
exports.useApolloClient = useApolloClient; | ||
exports.useMutation = useMutation; | ||
exports.useQuery = useQuery; | ||
exports.useSubscription = useSubscription; | ||
exports.resetApolloContext = exports.ApolloProvider = exports.ApolloConsumer = void 0; | ||
Object.defineProperty(exports, '__esModule', { value: true }); | ||
var _reactCommon = require("@apollo/react-common"); | ||
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } | ||
exports.getApolloContext = _reactCommon.getApolloContext; | ||
exports.ApolloConsumer = _reactCommon.ApolloConsumer; | ||
exports.ApolloProvider = _reactCommon.ApolloProvider; | ||
exports.resetApolloContext = _reactCommon.resetApolloContext; | ||
var reactCommon = require('@apollo/react-common'); | ||
var tslib = require('tslib'); | ||
var React = require('react'); | ||
var React__default = _interopDefault(React); | ||
var apolloClient = require('apollo-client'); | ||
var tsInvariant = require('ts-invariant'); | ||
require('fast-json-stable-stringify'); | ||
var _tslib = require("tslib"); | ||
/** | ||
* Copyright (c) Facebook, Inc. and its affiliates. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
* | ||
* | ||
*/ | ||
var _react = _interopRequireWildcard(require("react")); | ||
/** | ||
* Copyright (c) Facebook, Inc. and its affiliates. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
* | ||
* | ||
*/ | ||
var _apolloClient = require("apollo-client"); | ||
function isEqual(a, b) { | ||
if (a === b) { | ||
return true; | ||
var _apolloUtilities = require("apollo-utilities"); | ||
var _tsInvariant = require("ts-invariant"); | ||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } | ||
var OperationData = function () { | ||
function OperationData(options, context) { | ||
this.isMounted = true; | ||
this.previousOptions = {}; | ||
this.context = {}; | ||
this.options = {}; | ||
this.options = options || {}; | ||
this.context = context || {}; | ||
} | ||
OperationData.prototype.getOptions = function () { | ||
return this.options; | ||
}; | ||
OperationData.prototype.setOptions = function (newOptions) { | ||
if (!(0, _apolloUtilities.isEqual)(this.options, newOptions)) { | ||
this.previousOptions = this.options; | ||
} | ||
if (a instanceof Date && b instanceof Date) { | ||
return a.getTime() === b.getTime(); | ||
this.options = newOptions; | ||
}; | ||
OperationData.prototype.unmount = function () { | ||
this.isMounted = false; | ||
}; | ||
OperationData.prototype.refreshClient = function () { | ||
var client = this.options && this.options.client || this.context && this.context.client; | ||
process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(!!client, 2) : (0, _tsInvariant.invariant)(!!client, 'Could not find "client" in the context or passed in as an option. ' + 'Wrap the root component in an <ApolloProvider>, or pass an ' + 'ApolloClient instance in via options.'); | ||
var isNew = false; | ||
if (client !== this.client) { | ||
isNew = true; | ||
this.client = client; | ||
this.cleanup(); | ||
} | ||
if (a != null && | ||
typeof a === 'object' && | ||
b != null && | ||
typeof b === 'object') { | ||
for (var key in a) { | ||
if (Object.prototype.hasOwnProperty.call(a, key)) { | ||
if (!Object.prototype.hasOwnProperty.call(b, key)) { | ||
return false; | ||
} | ||
if (!isEqual(a[key], b[key])) { | ||
return false; | ||
} | ||
} | ||
} | ||
for (var key in b) { | ||
if (Object.prototype.hasOwnProperty.call(b, key) && | ||
!Object.prototype.hasOwnProperty.call(a, key)) { | ||
return false; | ||
} | ||
} | ||
return true; | ||
return { | ||
client: this.client, | ||
isNew: isNew | ||
}; | ||
}; | ||
OperationData.prototype.verifyDocumentType = function (document, type) { | ||
var operation = (0, _reactCommon.parser)(document); | ||
var requiredOperationName = (0, _reactCommon.operationName)(type); | ||
var usedOperationName = (0, _reactCommon.operationName)(operation.type); | ||
process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(operation.type === type, 3) : (0, _tsInvariant.invariant)(operation.type === type, "Running a " + requiredOperationName + " requires a graphql " + (requiredOperationName + ", but a " + usedOperationName + " was used instead.")); | ||
}; | ||
return OperationData; | ||
}(); | ||
var QueryData = function (_super) { | ||
(0, _tslib.__extends)(QueryData, _super); | ||
function QueryData(_a) { | ||
var options = _a.options, | ||
context = _a.context, | ||
forceUpdate = _a.forceUpdate; | ||
var _this = _super.call(this, options, context) || this; | ||
_this.previousData = {}; | ||
_this.currentObservable = {}; | ||
_this.forceUpdate = forceUpdate; | ||
return _this; | ||
} | ||
QueryData.prototype.execute = function () { | ||
var _this = this; | ||
this.refreshClient(); | ||
var _a = this.getOptions(), | ||
skip = _a.skip, | ||
query = _a.query; | ||
if (skip || query !== this.previousData.query) { | ||
this.removeQuerySubscription(); | ||
this.previousData.query = query; | ||
} | ||
return false; | ||
} | ||
var OperationData = (function () { | ||
function OperationData(options, context) { | ||
this._isMounted = true; | ||
this._options = {}; | ||
this._previousOptions = {}; | ||
this._context = {}; | ||
this._options = options || {}; | ||
this._context = context || {}; | ||
this.updateObservableQuery(); | ||
if (!skip) { | ||
this.startQuerySubscription(); | ||
} | ||
Object.defineProperty(OperationData.prototype, "isMounted", { | ||
get: function () { | ||
return this._isMounted; | ||
}, | ||
set: function (mounted) { | ||
this._isMounted = mounted; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(OperationData.prototype, "options", { | ||
get: function () { | ||
return this._options; | ||
}, | ||
set: function (newOptions) { | ||
if (!isEqual(this.options, newOptions)) { | ||
this.previousOptions = this.options; | ||
} | ||
this._options = newOptions; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(OperationData.prototype, "previousOptions", { | ||
get: function () { | ||
return this._previousOptions; | ||
}, | ||
set: function (newOptions) { | ||
this._previousOptions = newOptions; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(OperationData.prototype, "context", { | ||
get: function () { | ||
return this._context; | ||
}, | ||
set: function (newContext) { | ||
this._context = newContext; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(OperationData.prototype, "client", { | ||
get: function () { | ||
return this._client; | ||
}, | ||
set: function (newClient) { | ||
this._client = newClient; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
OperationData.prototype.unmount = function () { | ||
this.isMounted = false; | ||
var finish = function () { | ||
return _this.getQueryResult(); | ||
}; | ||
OperationData.prototype.refreshClient = function () { | ||
var client = (this.options && this.options.client) || | ||
(this.context && this.context.client); | ||
process.env.NODE_ENV === "production" ? tsInvariant.invariant(!!client) : tsInvariant.invariant(!!client, 'Could not find "client" in the context or passed in as an option. ' + | ||
'Wrap the root component in an <ApolloProvider>, or pass an ' + | ||
'ApolloClient instance in via options.'); | ||
var isNew = false; | ||
if (client !== this.client) { | ||
isNew = true; | ||
this.client = client; | ||
this.cleanup(); | ||
if (this.context && this.context.renderPromises) { | ||
var result = this.context.renderPromises.addQueryPromise(this, finish); | ||
return result || { | ||
loading: true, | ||
networkStatus: _apolloClient.NetworkStatus.loading | ||
}; | ||
} | ||
return finish(); | ||
}; | ||
QueryData.prototype.fetchData = function () { | ||
if (this.getOptions().skip) return false; | ||
var _a = this.getOptions(), | ||
children = _a.children, | ||
ssr = _a.ssr, | ||
displayName = _a.displayName, | ||
skip = _a.skip, | ||
onCompleted = _a.onCompleted, | ||
onError = _a.onError, | ||
partialRefetch = _a.partialRefetch, | ||
opts = (0, _tslib.__rest)(_a, ["children", "ssr", "displayName", "skip", "onCompleted", "onError", "partialRefetch"]); | ||
var fetchPolicy = opts.fetchPolicy; | ||
if (ssr === false) return false; | ||
if (fetchPolicy === 'network-only' || fetchPolicy === 'cache-and-network') { | ||
fetchPolicy = 'cache-first'; | ||
} | ||
var obs = this.refreshClient().client.watchQuery((0, _tslib.__assign)({}, opts, { | ||
fetchPolicy: fetchPolicy | ||
})); | ||
if (this.context && this.context.renderPromises) { | ||
this.context.renderPromises.registerSSRObservable(obs, this.getOptions()); | ||
} | ||
var result = this.currentObservable.query.getCurrentResult(); | ||
return result.loading ? obs.result() : false; | ||
}; | ||
QueryData.prototype.afterExecute = function () { | ||
this.isMounted = true; | ||
this.handleErrorOrCompleted(); | ||
return this.unmount.bind(this); | ||
}; | ||
QueryData.prototype.cleanup = function () { | ||
this.removeQuerySubscription(); | ||
this.currentObservable.query = null; | ||
this.previousData.result = null; | ||
}; | ||
QueryData.prototype.updateCurrentData = function () { | ||
if (this.isMounted) { | ||
this.forceUpdate(); | ||
} | ||
}; | ||
QueryData.prototype.prepareObservableQueryOptions = function () { | ||
this.verifyDocumentType(this.getOptions().query, _reactCommon.DocumentType.Query); | ||
var displayName = this.getOptions().displayName || 'Query'; | ||
return (0, _tslib.__assign)({}, this.getOptions(), { | ||
displayName: displayName, | ||
context: this.getOptions().context || {}, | ||
metadata: { | ||
reactComponent: { | ||
displayName: displayName | ||
} | ||
return { | ||
client: this.client, | ||
isNew: isNew | ||
}; | ||
} | ||
}); | ||
}; | ||
QueryData.prototype.observableQueryFields = function (observable) { | ||
return { | ||
variables: observable.variables, | ||
refetch: observable.refetch.bind(observable), | ||
fetchMore: observable.fetchMore.bind(observable), | ||
updateQuery: observable.updateQuery.bind(observable), | ||
startPolling: observable.startPolling.bind(observable), | ||
stopPolling: observable.stopPolling.bind(observable), | ||
subscribeToMore: observable.subscribeToMore.bind(observable) | ||
}; | ||
OperationData.prototype.verifyDocumentType = function (document, type) { | ||
var operation = reactCommon.parser(document); | ||
var requiredOperationName = reactCommon.operationName(type); | ||
var usedOperationName = reactCommon.operationName(operation.type); | ||
process.env.NODE_ENV === "production" ? tsInvariant.invariant(operation.type === type) : tsInvariant.invariant(operation.type === type, "Running a " + requiredOperationName + " requires a graphql " + | ||
(requiredOperationName + ", but a " + usedOperationName + " was used instead.")); | ||
}; | ||
return OperationData; | ||
}()); | ||
}; | ||
var QueryData = (function (_super) { | ||
tslib.__extends(QueryData, _super); | ||
function QueryData(_a) { | ||
var options = _a.options, context = _a.context, forceUpdate = _a.forceUpdate; | ||
var _this = _super.call(this, options, context) || this; | ||
_this.previousData = {}; | ||
_this.currentObservable = {}; | ||
_this.forceUpdate = forceUpdate; | ||
return _this; | ||
QueryData.prototype.initializeObservableQuery = function () { | ||
if (this.context && this.context.renderPromises) { | ||
this.currentObservable.query = this.context.renderPromises.getSSRObservable(this.getOptions()); | ||
} | ||
QueryData.prototype.execute = function () { | ||
var _this = this; | ||
this.refreshClient(); | ||
var _a = this.options, skip = _a.skip, query = _a.query; | ||
if (skip || query !== this.previousData.query) { | ||
this.removeQuerySubscription(); | ||
this.previousData.query = query; | ||
if (!this.currentObservable.query) { | ||
var observableQueryOptions = this.prepareObservableQueryOptions(); | ||
this.previousData.observableQueryOptions = (0, _tslib.__assign)({}, observableQueryOptions, { | ||
children: null | ||
}); | ||
this.currentObservable.query = this.refreshClient().client.watchQuery(observableQueryOptions); | ||
} | ||
}; | ||
QueryData.prototype.updateObservableQuery = function () { | ||
if (!this.currentObservable.query) { | ||
this.initializeObservableQuery(); | ||
} | ||
var newObservableQueryOptions = (0, _tslib.__assign)({}, this.prepareObservableQueryOptions(), { | ||
children: null | ||
}); | ||
if (!(0, _apolloUtilities.isEqual)(newObservableQueryOptions, this.previousData.observableQueryOptions)) { | ||
this.previousData.observableQueryOptions = newObservableQueryOptions; | ||
this.currentObservable.query.setOptions(newObservableQueryOptions).catch(function () {}); | ||
} | ||
}; | ||
QueryData.prototype.startQuerySubscription = function () { | ||
var _this = this; | ||
if (this.currentObservable.subscription) return; | ||
var obsQuery = this.currentObservable.query; | ||
this.currentObservable.subscription = obsQuery.subscribe({ | ||
next: function (_a) { | ||
var loading = _a.loading, | ||
networkStatus = _a.networkStatus, | ||
data = _a.data; | ||
if (_this.previousData.result && _this.previousData.result.loading === loading && _this.previousData.result.networkStatus === networkStatus && (0, _apolloUtilities.isEqual)(_this.previousData.result.data, data || {})) { | ||
return; | ||
} | ||
this.updateObservableQuery(); | ||
if (!skip) { | ||
this.startQuerySubscription(); | ||
_this.updateCurrentData(); | ||
}, | ||
error: function (error) { | ||
if (!_this.previousData.result || _this.previousData.result.networkStatus === _apolloClient.NetworkStatus.refetch) { | ||
_this.resubscribeToQuery(); | ||
} | ||
var finish = function () { return _this.getQueryResult(); }; | ||
if (this.context && this.context.renderPromises) { | ||
var result = this.context.renderPromises.addQueryPromise(this, finish); | ||
return result || { loading: true, networkStatus: apolloClient.NetworkStatus.loading }; | ||
} | ||
return finish(); | ||
if (!error.hasOwnProperty('graphQLErrors')) throw error; | ||
_this.updateCurrentData(); | ||
} | ||
}); | ||
}; | ||
QueryData.prototype.resubscribeToQuery = function () { | ||
this.removeQuerySubscription(); | ||
var lastError = this.currentObservable.query.getLastError(); | ||
var lastResult = this.currentObservable.query.getLastResult(); | ||
this.currentObservable.query.resetLastResults(); | ||
this.startQuerySubscription(); | ||
Object.assign(this.currentObservable.query, { | ||
lastError: lastError, | ||
lastResult: lastResult | ||
}); | ||
}; | ||
QueryData.prototype.getQueryResult = function () { | ||
var result = { | ||
data: Object.create(null) | ||
}; | ||
QueryData.prototype.fetchData = function () { | ||
if (this.options.skip) | ||
return false; | ||
var _a = this.options, children = _a.children, ssr = _a.ssr, displayName = _a.displayName, skip = _a.skip, onCompleted = _a.onCompleted, onError = _a.onError, partialRefetch = _a.partialRefetch, opts = tslib.__rest(_a, ["children", "ssr", "displayName", "skip", "onCompleted", "onError", "partialRefetch"]); | ||
var fetchPolicy = opts.fetchPolicy; | ||
if (ssr === false) | ||
return false; | ||
if (fetchPolicy === 'network-only' || fetchPolicy === 'cache-and-network') { | ||
fetchPolicy = 'cache-first'; | ||
} | ||
var obs = this.refreshClient().client.watchQuery(tslib.__assign({}, opts, { fetchPolicy: fetchPolicy })); | ||
if (this.context && this.context.renderPromises) { | ||
this.context.renderPromises.registerSSRObservable(obs, this.options); | ||
} | ||
var result = this.currentObservable.query.getCurrentResult(); | ||
return result.loading ? obs.result() : false; | ||
}; | ||
QueryData.prototype.afterExecute = function () { | ||
this.isMounted = true; | ||
this.handleErrorOrCompleted(); | ||
return this.unmount.bind(this); | ||
}; | ||
QueryData.prototype.cleanup = function () { | ||
this.removeQuerySubscription(); | ||
this.currentObservable.query = null; | ||
this.previousData.result = null; | ||
}; | ||
QueryData.prototype.updateCurrentData = function () { | ||
if (this.isMounted) { | ||
this.forceUpdate(); | ||
} | ||
}; | ||
QueryData.prototype.prepareObservableQueryOptions = function () { | ||
this.verifyDocumentType(this.options.query, reactCommon.DocumentType.Query); | ||
var displayName = this.options.displayName || 'Query'; | ||
return tslib.__assign({}, this.options, { displayName: displayName, context: this.options.context || {}, metadata: { reactComponent: { displayName: displayName } } }); | ||
}; | ||
QueryData.prototype.observableQueryFields = function (observable) { | ||
var fields = { | ||
variables: observable.variables, | ||
refetch: observable.refetch.bind(observable), | ||
fetchMore: observable.fetchMore.bind(observable), | ||
updateQuery: observable.updateQuery.bind(observable), | ||
startPolling: observable.startPolling.bind(observable), | ||
stopPolling: observable.stopPolling.bind(observable), | ||
subscribeToMore: observable.subscribeToMore.bind(observable) | ||
}; | ||
return fields; | ||
}; | ||
QueryData.prototype.initializeObservableQuery = function () { | ||
if (this.context && this.context.renderPromises) { | ||
this.currentObservable.query = this.context.renderPromises.getSSRObservable(this.options); | ||
} | ||
if (!this.currentObservable.query) { | ||
var observableQueryOptions = this.prepareObservableQueryOptions(); | ||
this.previousData.observableQueryOptions = tslib.__assign({}, observableQueryOptions, { children: null }); | ||
this.currentObservable.query = this.refreshClient().client.watchQuery(observableQueryOptions); | ||
} | ||
}; | ||
QueryData.prototype.updateObservableQuery = function () { | ||
if (!this.currentObservable.query) { | ||
this.initializeObservableQuery(); | ||
} | ||
var newObservableQueryOptions = tslib.__assign({}, this.prepareObservableQueryOptions(), { children: null }); | ||
if (!isEqual(newObservableQueryOptions, this.previousData.observableQueryOptions)) { | ||
this.previousData.observableQueryOptions = newObservableQueryOptions; | ||
this.currentObservable | ||
.query.setOptions(newObservableQueryOptions) | ||
.catch(function () { return null; }); | ||
} | ||
}; | ||
QueryData.prototype.startQuerySubscription = function () { | ||
var _this = this; | ||
if (this.currentObservable.subscription) | ||
return; | ||
var obsQuery = this.currentObservable.query; | ||
this.currentObservable.subscription = obsQuery.subscribe({ | ||
next: function (_a) { | ||
var loading = _a.loading, networkStatus = _a.networkStatus, data = _a.data; | ||
if (_this.previousData.result && | ||
_this.previousData.result.loading === loading && | ||
_this.previousData.result.networkStatus === networkStatus && | ||
isEqual(_this.previousData.result.data, data || {})) { | ||
return; | ||
} | ||
_this.updateCurrentData(); | ||
}, | ||
error: function (error) { | ||
if (!_this.previousData.result || | ||
_this.previousData.result.networkStatus === apolloClient.NetworkStatus.refetch) { | ||
_this.resubscribeToQuery(); | ||
} | ||
if (!error.hasOwnProperty('graphQLErrors')) | ||
throw error; | ||
_this.updateCurrentData(); | ||
} | ||
Object.assign(result, this.observableQueryFields(this.currentObservable.query)); | ||
if (this.getOptions().skip) { | ||
result = (0, _tslib.__assign)({}, result, { | ||
data: undefined, | ||
error: undefined, | ||
loading: false | ||
}); | ||
} else { | ||
var currentResult = this.currentObservable.query.getCurrentResult(); | ||
var loading = currentResult.loading, | ||
partial = currentResult.partial, | ||
networkStatus = currentResult.networkStatus, | ||
errors = currentResult.errors; | ||
var error = currentResult.error, | ||
data = currentResult.data; | ||
data = data || Object.create(null); | ||
if (errors && errors.length > 0) { | ||
error = new _apolloClient.ApolloError({ | ||
graphQLErrors: errors | ||
}); | ||
}; | ||
QueryData.prototype.resubscribeToQuery = function () { | ||
this.removeQuerySubscription(); | ||
var lastError = this.currentObservable.query.getLastError(); | ||
var lastResult = this.currentObservable.query.getLastResult(); | ||
this.currentObservable.query.resetLastResults(); | ||
this.startQuerySubscription(); | ||
Object.assign(this.currentObservable.query, { | ||
lastError: lastError, | ||
lastResult: lastResult | ||
} | ||
Object.assign(result, { | ||
loading: loading, | ||
networkStatus: networkStatus, | ||
error: error | ||
}); | ||
if (loading) { | ||
var previousData = this.previousData.result ? this.previousData.result.data : {}; | ||
Object.assign(result.data, previousData, data); | ||
} else if (error) { | ||
Object.assign(result, { | ||
data: (this.currentObservable.query.getLastResult() || {}).data | ||
}); | ||
}; | ||
QueryData.prototype.getQueryResult = function () { | ||
var result = { | ||
data: Object.create(null) | ||
}; | ||
Object.assign(result, this.observableQueryFields(this.currentObservable.query)); | ||
if (this.options.skip) { | ||
result = tslib.__assign({}, result, { data: undefined, error: undefined, loading: false }); | ||
} else { | ||
var fetchPolicy = this.currentObservable.query.options.fetchPolicy; | ||
var partialRefetch = this.getOptions().partialRefetch; | ||
if (partialRefetch && Object.keys(data).length === 0 && partial && fetchPolicy !== 'cache-only') { | ||
Object.assign(result, { | ||
loading: true, | ||
networkStatus: _apolloClient.NetworkStatus.loading | ||
}); | ||
result.refetch(); | ||
return result; | ||
} | ||
else { | ||
var currentResult = this.currentObservable.query.getCurrentResult(); | ||
var loading = currentResult.loading, partial = currentResult.partial, networkStatus = currentResult.networkStatus, errors = currentResult.errors; | ||
var error = currentResult.error, data = currentResult.data; | ||
data = data || Object.create(null); | ||
if (errors && errors.length > 0) { | ||
error = new apolloClient.ApolloError({ graphQLErrors: errors }); | ||
} | ||
Object.assign(result, { loading: loading, networkStatus: networkStatus, error: error }); | ||
if (loading) { | ||
var previousData = this.previousData.result | ||
? this.previousData.result.data | ||
: {}; | ||
Object.assign(result.data, previousData, data); | ||
} | ||
else if (error) { | ||
Object.assign(result, { | ||
data: (this.currentObservable.query.getLastResult() || {}) | ||
.data | ||
}); | ||
} | ||
else { | ||
var fetchPolicy = this.currentObservable.query.options.fetchPolicy; | ||
var partialRefetch = this.options.partialRefetch; | ||
if (partialRefetch && | ||
Object.keys(data).length === 0 && | ||
partial && | ||
fetchPolicy !== 'cache-only') { | ||
Object.assign(result, { | ||
loading: true, | ||
networkStatus: apolloClient.NetworkStatus.loading | ||
}); | ||
result.refetch(); | ||
return result; | ||
} | ||
Object.assign(result.data, data); | ||
} | ||
} | ||
result.client = this.client; | ||
this.previousData.loading = | ||
(this.previousData.result && this.previousData.result.loading) || false; | ||
this.previousData.result = result; | ||
return result; | ||
}; | ||
QueryData.prototype.handleErrorOrCompleted = function () { | ||
var _a = this.currentObservable.query.getCurrentResult(), data = _a.data, loading = _a.loading, error = _a.error; | ||
if (!loading) { | ||
var _b = this.options, query = _b.query, variables = _b.variables, onCompleted = _b.onCompleted, onError = _b.onError; | ||
if (this.previousOptions && | ||
isEqual(this.previousOptions.query, query) && | ||
isEqual(this.previousOptions.variables, variables) && | ||
!this.previousData.loading) { | ||
return; | ||
} | ||
if (onCompleted && !error) { | ||
onCompleted(data); | ||
} | ||
else if (onError && error) { | ||
onError(error); | ||
} | ||
} | ||
}; | ||
QueryData.prototype.removeQuerySubscription = function () { | ||
if (this.currentObservable.subscription) { | ||
this.currentObservable.subscription.unsubscribe(); | ||
delete this.currentObservable.subscription; | ||
} | ||
}; | ||
return QueryData; | ||
}(OperationData)); | ||
Object.assign(result.data, data); | ||
} | ||
} | ||
result.client = this.client; | ||
this.previousData.loading = this.previousData.result && this.previousData.result.loading || false; | ||
this.previousData.result = result; | ||
return result; | ||
}; | ||
QueryData.prototype.handleErrorOrCompleted = function () { | ||
var _a = this.currentObservable.query.getCurrentResult(), | ||
data = _a.data, | ||
loading = _a.loading, | ||
error = _a.error; | ||
if (!loading) { | ||
var _b = this.getOptions(), | ||
query = _b.query, | ||
variables = _b.variables, | ||
onCompleted = _b.onCompleted, | ||
onError = _b.onError; | ||
if (this.previousOptions && !this.previousData.loading && (0, _apolloUtilities.isEqual)(this.previousOptions.query, query) && (0, _apolloUtilities.isEqual)(this.previousOptions.variables, variables)) { | ||
return; | ||
} | ||
if (onCompleted && !error) { | ||
onCompleted(data); | ||
} else if (onError && error) { | ||
onError(error); | ||
} | ||
} | ||
}; | ||
QueryData.prototype.removeQuerySubscription = function () { | ||
if (this.currentObservable.subscription) { | ||
this.currentObservable.subscription.unsubscribe(); | ||
delete this.currentObservable.subscription; | ||
} | ||
}; | ||
return QueryData; | ||
}(OperationData); | ||
function useQuery(query, options) { | ||
var context = React.useContext(reactCommon.getApolloContext()); | ||
var _a = React.useReducer(function (x) { return x + 1; }, 0), _ignored = _a[0], forceUpdate = _a[1]; | ||
var updatedOptions = options ? tslib.__assign({}, options, { query: query }) : { query: query }; | ||
var queryDataRef = React.useRef(); | ||
function getQueryDataRef() { | ||
if (!queryDataRef.current) { | ||
queryDataRef.current = new QueryData({ | ||
options: updatedOptions, | ||
context: context, | ||
forceUpdate: forceUpdate | ||
}); | ||
} | ||
return queryDataRef.current; | ||
var context = (0, _react.useContext)((0, _reactCommon.getApolloContext)()); | ||
var _a = (0, _react.useReducer)(function (x) { | ||
return x + 1; | ||
}, 0), | ||
_ignored = _a[0], | ||
forceUpdate = _a[1]; | ||
var updatedOptions = options ? (0, _tslib.__assign)({}, options, { | ||
query: query | ||
}) : { | ||
query: query | ||
}; | ||
var queryDataRef = (0, _react.useRef)(); | ||
function getQueryDataRef() { | ||
if (!queryDataRef.current) { | ||
queryDataRef.current = new QueryData({ | ||
options: updatedOptions, | ||
context: context, | ||
forceUpdate: forceUpdate | ||
}); | ||
} | ||
var queryData = getQueryDataRef(); | ||
queryData.options = updatedOptions; | ||
queryData.context = context; | ||
React.useEffect(function () { | ||
return queryData.afterExecute(); | ||
}); | ||
return queryData.execute(); | ||
return queryDataRef.current; | ||
} | ||
var queryData = getQueryDataRef(); | ||
queryData.setOptions(updatedOptions); | ||
queryData.context = context; | ||
(0, _react.useEffect)(function () { | ||
return queryData.afterExecute(); | ||
}); | ||
return queryData.execute(); | ||
} | ||
var MutationData = (function (_super) { | ||
tslib.__extends(MutationData, _super); | ||
function MutationData(_a) { | ||
var options = _a.options, context = _a.context, result = _a.result, setResult = _a.setResult; | ||
var _this = _super.call(this, options, context) || this; | ||
_this.verifyDocumentType(options.mutation, reactCommon.DocumentType.Mutation); | ||
_this.result = result; | ||
_this.setResult = setResult; | ||
_this.mostRecentMutationId = 0; | ||
return _this; | ||
var MutationData = function (_super) { | ||
(0, _tslib.__extends)(MutationData, _super); | ||
function MutationData(_a) { | ||
var options = _a.options, | ||
context = _a.context, | ||
result = _a.result, | ||
setResult = _a.setResult; | ||
var _this = _super.call(this, options, context) || this; | ||
_this.verifyDocumentType(options.mutation, _reactCommon.DocumentType.Mutation); | ||
_this.result = result; | ||
_this.setResult = setResult; | ||
_this.mostRecentMutationId = 0; | ||
return _this; | ||
} | ||
MutationData.prototype.execute = function (result) { | ||
var _this = this; | ||
this.verifyDocumentType(this.getOptions().mutation, _reactCommon.DocumentType.Mutation); | ||
var runMutation = function (options) { | ||
return _this.runMutation(options); | ||
}; | ||
return [runMutation, result]; | ||
}; | ||
MutationData.prototype.afterExecute = function () { | ||
this.isMounted = true; | ||
return this.unmount.bind(this); | ||
}; | ||
MutationData.prototype.cleanup = function () {}; | ||
MutationData.prototype.runMutation = function (mutationFunctionOptions) { | ||
var _this = this; | ||
if (mutationFunctionOptions === void 0) { | ||
mutationFunctionOptions = {}; | ||
} | ||
MutationData.prototype.execute = function (result) { | ||
var _this = this; | ||
this.verifyDocumentType(this.options.mutation, reactCommon.DocumentType.Mutation); | ||
var runMutation = function (options) { return _this.runMutation(options); }; | ||
return [runMutation, result]; | ||
this.onMutationStart(); | ||
var mutationId = this.generateNewMutationId(); | ||
return this.mutate(mutationFunctionOptions).then(function (response) { | ||
_this.onMutationCompleted(response, mutationId); | ||
return response; | ||
}).catch(function (error) { | ||
_this.onMutationError(error, mutationId); | ||
if (!_this.getOptions().onError) throw error; | ||
}); | ||
}; | ||
MutationData.prototype.mutate = function (mutationFunctionOptions) { | ||
var _a = this.getOptions(), | ||
mutation = _a.mutation, | ||
variables = _a.variables, | ||
optimisticResponse = _a.optimisticResponse, | ||
update = _a.update, | ||
_b = _a.context, | ||
mutationContext = _b === void 0 ? {} : _b, | ||
_c = _a.awaitRefetchQueries, | ||
awaitRefetchQueries = _c === void 0 ? false : _c, | ||
fetchPolicy = _a.fetchPolicy; | ||
var mutateOptions = (0, _tslib.__assign)({}, mutationFunctionOptions); | ||
var mutateVariables = Object.assign({}, variables, mutateOptions.variables); | ||
delete mutateOptions.variables; | ||
return this.refreshClient().client.mutate((0, _tslib.__assign)({ | ||
mutation: mutation, | ||
optimisticResponse: optimisticResponse, | ||
refetchQueries: mutateOptions.refetchQueries || this.getOptions().refetchQueries, | ||
awaitRefetchQueries: awaitRefetchQueries, | ||
update: update, | ||
context: mutationContext, | ||
fetchPolicy: fetchPolicy, | ||
variables: mutateVariables | ||
}, mutateOptions)); | ||
}; | ||
MutationData.prototype.onMutationStart = function () { | ||
if (!this.result.loading && !this.getOptions().ignoreResults) { | ||
this.updateResult({ | ||
loading: true, | ||
error: undefined, | ||
data: undefined, | ||
called: true | ||
}); | ||
} | ||
}; | ||
MutationData.prototype.onMutationCompleted = function (response, mutationId) { | ||
var _a = this.getOptions(), | ||
onCompleted = _a.onCompleted, | ||
ignoreResults = _a.ignoreResults; | ||
var data = response.data, | ||
errors = response.errors; | ||
var error = errors && errors.length > 0 ? new _apolloClient.ApolloError({ | ||
graphQLErrors: errors | ||
}) : undefined; | ||
var callOncomplete = function () { | ||
return onCompleted ? onCompleted(data) : null; | ||
}; | ||
MutationData.prototype.afterExecute = function () { | ||
this.isMounted = true; | ||
return this.unmount.bind(this); | ||
}; | ||
MutationData.prototype.cleanup = function () { | ||
}; | ||
MutationData.prototype.runMutation = function (mutationFunctionOptions) { | ||
var _this = this; | ||
if (mutationFunctionOptions === void 0) { mutationFunctionOptions = {}; } | ||
this.onMutationStart(); | ||
var mutationId = this.generateNewMutationId(); | ||
return this.mutate(mutationFunctionOptions) | ||
.then(function (response) { | ||
_this.onMutationCompleted(response, mutationId); | ||
return response; | ||
}) | ||
.catch(function (error) { | ||
_this.onMutationError(error, mutationId); | ||
if (!_this.options.onError) | ||
throw error; | ||
}); | ||
}; | ||
MutationData.prototype.mutate = function (mutationFunctionOptions) { | ||
var _a = this.options, mutation = _a.mutation, variables = _a.variables, optimisticResponse = _a.optimisticResponse, update = _a.update, _b = _a.context, mutationContext = _b === void 0 ? {} : _b, _c = _a.awaitRefetchQueries, awaitRefetchQueries = _c === void 0 ? false : _c, fetchPolicy = _a.fetchPolicy; | ||
var mutateOptions = tslib.__assign({}, mutationFunctionOptions); | ||
var refetchQueries = mutateOptions.refetchQueries || this.options.refetchQueries; | ||
var mutateVariables = Object.assign({}, variables, mutateOptions.variables); | ||
delete mutateOptions.variables; | ||
return this.refreshClient().client.mutate(tslib.__assign({ mutation: mutation, | ||
optimisticResponse: optimisticResponse, | ||
refetchQueries: refetchQueries, | ||
awaitRefetchQueries: awaitRefetchQueries, | ||
update: update, context: mutationContext, fetchPolicy: fetchPolicy, variables: mutateVariables }, mutateOptions)); | ||
}; | ||
MutationData.prototype.onMutationStart = function () { | ||
if (!this.result.loading && !this.options.ignoreResults) { | ||
this.updateResult({ | ||
loading: true, | ||
error: undefined, | ||
data: undefined, | ||
called: true | ||
}); | ||
} | ||
}; | ||
MutationData.prototype.onMutationCompleted = function (response, mutationId) { | ||
var _a = this.options, onCompleted = _a.onCompleted, ignoreResults = _a.ignoreResults; | ||
var data = response.data, errors = response.errors; | ||
var error = errors && errors.length > 0 | ||
? new apolloClient.ApolloError({ graphQLErrors: errors }) | ||
: undefined; | ||
var callOncomplete = function () { | ||
return onCompleted ? onCompleted(data) : null; | ||
}; | ||
if (this.isMostRecentMutation(mutationId) && !ignoreResults) { | ||
this.updateResult({ | ||
called: true, | ||
loading: false, | ||
data: data, | ||
error: error | ||
}); | ||
} | ||
callOncomplete(); | ||
}; | ||
MutationData.prototype.onMutationError = function (error, mutationId) { | ||
var onError = this.options.onError; | ||
var callOnError = function () { return (onError ? onError(error) : null); }; | ||
if (this.isMostRecentMutation(mutationId)) { | ||
this.updateResult({ | ||
loading: false, | ||
error: error, | ||
data: undefined, | ||
called: true | ||
}); | ||
} | ||
callOnError(); | ||
}; | ||
MutationData.prototype.generateNewMutationId = function () { | ||
this.mostRecentMutationId += 1; | ||
return this.mostRecentMutationId; | ||
}; | ||
MutationData.prototype.isMostRecentMutation = function (mutationId) { | ||
return this.mostRecentMutationId === mutationId; | ||
}; | ||
MutationData.prototype.updateResult = function (result) { | ||
if (this.isMounted && | ||
(!this.previousResult || !isEqual(this.previousResult, result))) { | ||
this.setResult(result); | ||
this.previousResult = result; | ||
} | ||
}; | ||
return MutationData; | ||
}(OperationData)); | ||
if (this.isMostRecentMutation(mutationId) && !ignoreResults) { | ||
this.updateResult({ | ||
called: true, | ||
loading: false, | ||
data: data, | ||
error: error | ||
}); | ||
} | ||
callOncomplete(); | ||
}; | ||
MutationData.prototype.onMutationError = function (error, mutationId) { | ||
var onError = this.getOptions().onError; | ||
if (this.isMostRecentMutation(mutationId)) { | ||
this.updateResult({ | ||
loading: false, | ||
error: error, | ||
data: undefined, | ||
called: true | ||
}); | ||
} | ||
if (onError) { | ||
onError(error); | ||
} | ||
}; | ||
MutationData.prototype.generateNewMutationId = function () { | ||
return ++this.mostRecentMutationId; | ||
}; | ||
MutationData.prototype.isMostRecentMutation = function (mutationId) { | ||
return this.mostRecentMutationId === mutationId; | ||
}; | ||
MutationData.prototype.updateResult = function (result) { | ||
if (this.isMounted && (!this.previousResult || !(0, _apolloUtilities.isEqual)(this.previousResult, result))) { | ||
this.setResult(result); | ||
this.previousResult = result; | ||
} | ||
}; | ||
return MutationData; | ||
}(OperationData); | ||
function useMutation(mutation, options) { | ||
var context = React.useContext(reactCommon.getApolloContext()); | ||
var _a = React.useState({ called: false, loading: false }), result = _a[0], setResult = _a[1]; | ||
var updatedOptions = options ? tslib.__assign({}, options, { mutation: mutation }) : { mutation: mutation }; | ||
var mutationDataRef = React.useRef(); | ||
function getMutationDataRef() { | ||
if (!mutationDataRef.current) { | ||
mutationDataRef.current = new MutationData({ | ||
options: updatedOptions, | ||
context: context, | ||
result: result, | ||
setResult: setResult | ||
}); | ||
} | ||
return mutationDataRef.current; | ||
var context = (0, _react.useContext)((0, _reactCommon.getApolloContext)()); | ||
var _a = (0, _react.useState)({ | ||
called: false, | ||
loading: false | ||
}), | ||
result = _a[0], | ||
setResult = _a[1]; | ||
var updatedOptions = options ? (0, _tslib.__assign)({}, options, { | ||
mutation: mutation | ||
}) : { | ||
mutation: mutation | ||
}; | ||
var mutationDataRef = (0, _react.useRef)(); | ||
function getMutationDataRef() { | ||
if (!mutationDataRef.current) { | ||
mutationDataRef.current = new MutationData({ | ||
options: updatedOptions, | ||
context: context, | ||
result: result, | ||
setResult: setResult | ||
}); | ||
} | ||
var mutationData = getMutationDataRef(); | ||
mutationData.options = updatedOptions; | ||
mutationData.context = context; | ||
React.useEffect(function () { | ||
return mutationData.afterExecute(); | ||
}); | ||
return mutationData.execute(result); | ||
return mutationDataRef.current; | ||
} | ||
var mutationData = getMutationDataRef(); | ||
mutationData.setOptions(updatedOptions); | ||
mutationData.context = context; | ||
(0, _react.useEffect)(function () { | ||
return mutationData.afterExecute(); | ||
}); | ||
return mutationData.execute(result); | ||
} | ||
var SubscriptionData = (function (_super) { | ||
tslib.__extends(SubscriptionData, _super); | ||
function SubscriptionData(_a) { | ||
var options = _a.options, context = _a.context, setResult = _a.setResult; | ||
var _this = _super.call(this, options, context) || this; | ||
_this.currentObservable = {}; | ||
_this.setResult = setResult; | ||
_this.initialize(options); | ||
return _this; | ||
var SubscriptionData = function (_super) { | ||
(0, _tslib.__extends)(SubscriptionData, _super); | ||
function SubscriptionData(_a) { | ||
var options = _a.options, | ||
context = _a.context, | ||
setResult = _a.setResult; | ||
var _this = _super.call(this, options, context) || this; | ||
_this.currentObservable = {}; | ||
_this.setResult = setResult; | ||
_this.initialize(options); | ||
return _this; | ||
} | ||
SubscriptionData.prototype.execute = function (result) { | ||
var currentResult = result; | ||
if (this.refreshClient().isNew) { | ||
currentResult = this.getLoadingResult(); | ||
} | ||
SubscriptionData.prototype.execute = function (result) { | ||
var currentResult = result; | ||
if (this.refreshClient().isNew) { | ||
currentResult = this.getLoadingResult(); | ||
} | ||
var shouldResubscribe = this.options.shouldResubscribe; | ||
if (typeof shouldResubscribe === 'function') { | ||
shouldResubscribe = !!shouldResubscribe(this.options); | ||
} | ||
if (shouldResubscribe !== false && | ||
this.previousOptions && | ||
Object.keys(this.previousOptions).length > 0 && | ||
(!isEqual(this.previousOptions.variables, this.options.variables) || | ||
this.previousOptions.subscription !== this.options.subscription)) { | ||
this.endSubscription(); | ||
delete this.currentObservable.query; | ||
currentResult = this.getLoadingResult(); | ||
} | ||
this.initialize(this.options); | ||
this.startSubscription(); | ||
this.previousOptions = this.options; | ||
return tslib.__assign({}, currentResult, { variables: this.options.variables }); | ||
var shouldResubscribe = this.getOptions().shouldResubscribe; | ||
if (typeof shouldResubscribe === 'function') { | ||
shouldResubscribe = !!shouldResubscribe(this.getOptions()); | ||
} | ||
if (shouldResubscribe !== false && this.previousOptions && Object.keys(this.previousOptions).length > 0 && (this.previousOptions.subscription !== this.getOptions().subscription || !(0, _apolloUtilities.isEqual)(this.previousOptions.variables, this.getOptions().variables))) { | ||
this.endSubscription(); | ||
delete this.currentObservable.query; | ||
currentResult = this.getLoadingResult(); | ||
} | ||
this.initialize(this.getOptions()); | ||
this.startSubscription(); | ||
this.previousOptions = this.getOptions(); | ||
return (0, _tslib.__assign)({}, currentResult, { | ||
variables: this.getOptions().variables | ||
}); | ||
}; | ||
SubscriptionData.prototype.afterExecute = function () { | ||
this.isMounted = true; | ||
return this.unmount.bind(this); | ||
}; | ||
SubscriptionData.prototype.cleanup = function () { | ||
this.endSubscription(); | ||
delete this.currentObservable.query; | ||
}; | ||
SubscriptionData.prototype.initialize = function (options) { | ||
if (this.currentObservable.query) return; | ||
this.currentObservable.query = this.refreshClient().client.subscribe({ | ||
query: options.subscription, | ||
variables: options.variables, | ||
fetchPolicy: options.fetchPolicy | ||
}); | ||
}; | ||
SubscriptionData.prototype.startSubscription = function () { | ||
if (this.currentObservable.subscription) return; | ||
this.currentObservable.subscription = this.currentObservable.query.subscribe({ | ||
next: this.updateCurrentData.bind(this), | ||
error: this.updateError.bind(this), | ||
complete: this.completeSubscription.bind(this) | ||
}); | ||
}; | ||
SubscriptionData.prototype.getLoadingResult = function () { | ||
return { | ||
loading: true, | ||
error: undefined, | ||
data: undefined | ||
}; | ||
SubscriptionData.prototype.afterExecute = function () { | ||
this.isMounted = true; | ||
return this.unmount.bind(this); | ||
}; | ||
SubscriptionData.prototype.cleanup = function () { | ||
this.endSubscription(); | ||
delete this.currentObservable.query; | ||
}; | ||
SubscriptionData.prototype.initialize = function (options) { | ||
if (this.currentObservable.query) | ||
return; | ||
this.currentObservable.query = this.refreshClient().client.subscribe({ | ||
query: options.subscription, | ||
variables: options.variables, | ||
fetchPolicy: options.fetchPolicy | ||
}); | ||
}; | ||
SubscriptionData.prototype.startSubscription = function () { | ||
if (this.currentObservable.subscription) | ||
return; | ||
this.currentObservable.subscription = this.currentObservable.query.subscribe({ | ||
next: this.updateCurrentData.bind(this), | ||
error: this.updateError.bind(this), | ||
complete: this.completeSubscription.bind(this) | ||
}); | ||
}; | ||
SubscriptionData.prototype.getLoadingResult = function () { | ||
return { | ||
loading: true, | ||
error: undefined, | ||
data: undefined | ||
}; | ||
}; | ||
SubscriptionData.prototype.updateResult = function (result) { | ||
if (this.isMounted) { | ||
this.setResult(result); | ||
} | ||
}; | ||
SubscriptionData.prototype.updateCurrentData = function (result) { | ||
var onSubscriptionData = this.options.onSubscriptionData; | ||
if (onSubscriptionData) { | ||
onSubscriptionData({ | ||
client: this.refreshClient().client, | ||
subscriptionData: result | ||
}); | ||
} | ||
this.updateResult({ | ||
data: result.data, | ||
loading: false, | ||
error: undefined | ||
}); | ||
}; | ||
SubscriptionData.prototype.updateError = function (error) { | ||
this.updateResult({ | ||
error: error, | ||
loading: false | ||
}); | ||
}; | ||
SubscriptionData.prototype.completeSubscription = function () { | ||
var onSubscriptionComplete = this.options.onSubscriptionComplete; | ||
if (onSubscriptionComplete) | ||
onSubscriptionComplete(); | ||
this.endSubscription(); | ||
}; | ||
SubscriptionData.prototype.endSubscription = function () { | ||
if (this.currentObservable.subscription) { | ||
this.currentObservable.subscription.unsubscribe(); | ||
delete this.currentObservable.subscription; | ||
} | ||
}; | ||
return SubscriptionData; | ||
}(OperationData)); | ||
}; | ||
SubscriptionData.prototype.updateResult = function (result) { | ||
if (this.isMounted) { | ||
this.setResult(result); | ||
} | ||
}; | ||
SubscriptionData.prototype.updateCurrentData = function (result) { | ||
var onSubscriptionData = this.getOptions().onSubscriptionData; | ||
if (onSubscriptionData) { | ||
onSubscriptionData({ | ||
client: this.refreshClient().client, | ||
subscriptionData: result | ||
}); | ||
} | ||
this.updateResult({ | ||
data: result.data, | ||
loading: false, | ||
error: undefined | ||
}); | ||
}; | ||
SubscriptionData.prototype.updateError = function (error) { | ||
this.updateResult({ | ||
error: error, | ||
loading: false | ||
}); | ||
}; | ||
SubscriptionData.prototype.completeSubscription = function () { | ||
var onSubscriptionComplete = this.getOptions().onSubscriptionComplete; | ||
if (onSubscriptionComplete) onSubscriptionComplete(); | ||
this.endSubscription(); | ||
}; | ||
SubscriptionData.prototype.endSubscription = function () { | ||
if (this.currentObservable.subscription) { | ||
this.currentObservable.subscription.unsubscribe(); | ||
delete this.currentObservable.subscription; | ||
} | ||
}; | ||
return SubscriptionData; | ||
}(OperationData); | ||
function useSubscription(subscription, options) { | ||
var context = React.useContext(reactCommon.getApolloContext()); | ||
var _a = React.useState({ | ||
loading: true, | ||
error: undefined, | ||
data: undefined | ||
}), result = _a[0], setResult = _a[1]; | ||
var updatedOptions = options | ||
? tslib.__assign({}, options, { subscription: subscription }) : { subscription: subscription }; | ||
var subscriptionDataRef = React.useRef(); | ||
function getSubscriptionDataRef() { | ||
if (!subscriptionDataRef.current) { | ||
subscriptionDataRef.current = new SubscriptionData({ | ||
options: updatedOptions, | ||
context: context, | ||
setResult: setResult | ||
}); | ||
} | ||
return subscriptionDataRef.current; | ||
var context = (0, _react.useContext)((0, _reactCommon.getApolloContext)()); | ||
var _a = (0, _react.useState)({ | ||
loading: true, | ||
error: undefined, | ||
data: undefined | ||
}), | ||
result = _a[0], | ||
setResult = _a[1]; | ||
var updatedOptions = options ? (0, _tslib.__assign)({}, options, { | ||
subscription: subscription | ||
}) : { | ||
subscription: subscription | ||
}; | ||
var subscriptionDataRef = (0, _react.useRef)(); | ||
function getSubscriptionDataRef() { | ||
if (!subscriptionDataRef.current) { | ||
subscriptionDataRef.current = new SubscriptionData({ | ||
options: updatedOptions, | ||
context: context, | ||
setResult: setResult | ||
}); | ||
} | ||
var subscriptionData = getSubscriptionDataRef(); | ||
subscriptionData.options = updatedOptions; | ||
subscriptionData.context = context; | ||
React.useEffect(function () { | ||
return subscriptionData.afterExecute(); | ||
}); | ||
return subscriptionData.execute(result); | ||
return subscriptionDataRef.current; | ||
} | ||
var subscriptionData = getSubscriptionDataRef(); | ||
subscriptionData.setOptions(updatedOptions); | ||
subscriptionData.context = context; | ||
(0, _react.useEffect)(function () { | ||
return subscriptionData.afterExecute(); | ||
}); | ||
return subscriptionData.execute(result); | ||
} | ||
function useApolloClient() { | ||
var client = React__default.useContext(reactCommon.getApolloContext()).client; | ||
process.env.NODE_ENV === "production" ? tsInvariant.invariant(client) : tsInvariant.invariant(client, 'No Apollo Client instance can be found. Please ensure that you ' + | ||
'have called `ApolloProvider` higher up in your tree.'); | ||
return client; | ||
var client = _react.default.useContext((0, _reactCommon.getApolloContext)()).client; | ||
process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(client, 1) : (0, _tsInvariant.invariant)(client, 'No Apollo Client instance can be found. Please ensure that you ' + 'have called `ApolloProvider` higher up in your tree.'); | ||
return client; | ||
} | ||
function makeDefaultQueryInfo() { | ||
return { | ||
seen: false, | ||
observable: null | ||
}; | ||
return { | ||
seen: false, | ||
observable: null | ||
}; | ||
} | ||
var RenderPromises = (function () { | ||
function RenderPromises() { | ||
this.queryPromises = new Map(); | ||
this.queryInfoTrie = new Map(); | ||
var RenderPromises = function () { | ||
function RenderPromises() { | ||
this.queryPromises = new Map(); | ||
this.queryInfoTrie = new Map(); | ||
} | ||
RenderPromises.prototype.registerSSRObservable = function (observable, props) { | ||
this.lookupQueryInfo(props).observable = observable; | ||
}; | ||
RenderPromises.prototype.getSSRObservable = function (props) { | ||
return this.lookupQueryInfo(props).observable; | ||
}; | ||
RenderPromises.prototype.addQueryPromise = function (queryInstance, finish) { | ||
var info = this.lookupQueryInfo(queryInstance.getOptions()); | ||
if (!info.seen) { | ||
this.queryPromises.set(queryInstance.getOptions(), new Promise(function (resolve) { | ||
resolve(queryInstance.fetchData()); | ||
})); | ||
return null; | ||
} | ||
RenderPromises.prototype.registerSSRObservable = function (observable, props) { | ||
this.lookupQueryInfo(props).observable = observable; | ||
}; | ||
RenderPromises.prototype.getSSRObservable = function (props) { | ||
return this.lookupQueryInfo(props).observable; | ||
}; | ||
RenderPromises.prototype.addQueryPromise = function (queryInstance, finish) { | ||
var info = this.lookupQueryInfo(queryInstance.options); | ||
if (!info.seen) { | ||
this.queryPromises.set(queryInstance.options, new Promise(function (resolve) { | ||
resolve(queryInstance.fetchData()); | ||
})); | ||
return null; | ||
} | ||
return finish(); | ||
}; | ||
RenderPromises.prototype.hasPromises = function () { | ||
return this.queryPromises.size > 0; | ||
}; | ||
RenderPromises.prototype.consumeAndAwaitPromises = function () { | ||
var _this = this; | ||
var promises = []; | ||
this.queryPromises.forEach(function (promise, queryInstance) { | ||
_this.lookupQueryInfo(queryInstance).seen = true; | ||
promises.push(promise); | ||
}); | ||
this.queryPromises.clear(); | ||
return Promise.all(promises); | ||
}; | ||
RenderPromises.prototype.lookupQueryInfo = function (props) { | ||
var queryInfoTrie = this.queryInfoTrie; | ||
var query = props.query, variables = props.variables; | ||
var varMap = queryInfoTrie.get(query) || new Map(); | ||
if (!queryInfoTrie.has(query)) | ||
queryInfoTrie.set(query, varMap); | ||
var variablesString = JSON.stringify(variables); | ||
var info = varMap.get(variablesString) || makeDefaultQueryInfo(); | ||
if (!varMap.has(variablesString)) | ||
varMap.set(variablesString, info); | ||
return info; | ||
}; | ||
return RenderPromises; | ||
}()); | ||
return finish(); | ||
}; | ||
RenderPromises.prototype.hasPromises = function () { | ||
return this.queryPromises.size > 0; | ||
}; | ||
RenderPromises.prototype.consumeAndAwaitPromises = function () { | ||
var _this = this; | ||
var promises = []; | ||
this.queryPromises.forEach(function (promise, queryInstance) { | ||
_this.lookupQueryInfo(queryInstance).seen = true; | ||
promises.push(promise); | ||
}); | ||
this.queryPromises.clear(); | ||
return Promise.all(promises); | ||
}; | ||
RenderPromises.prototype.lookupQueryInfo = function (props) { | ||
var queryInfoTrie = this.queryInfoTrie; | ||
var query = props.query, | ||
variables = props.variables; | ||
var varMap = queryInfoTrie.get(query) || new Map(); | ||
if (!queryInfoTrie.has(query)) queryInfoTrie.set(query, varMap); | ||
var variablesString = JSON.stringify(variables); | ||
var info = varMap.get(variablesString) || makeDefaultQueryInfo(); | ||
if (!varMap.has(variablesString)) varMap.set(variablesString, info); | ||
return info; | ||
}; | ||
return RenderPromises; | ||
}(); | ||
function getDataFromTree(tree, context) { | ||
if (context === void 0) { context = {}; } | ||
return getMarkupFromTree({ | ||
tree: tree, | ||
context: context, | ||
renderFunction: require('react-dom/server').renderToStaticMarkup | ||
}); | ||
if (context === void 0) { | ||
context = {}; | ||
} | ||
return getMarkupFromTree({ | ||
tree: tree, | ||
context: context, | ||
renderFunction: require('react-dom/server').renderToStaticMarkup | ||
}); | ||
} | ||
function getMarkupFromTree(_a) { | ||
var tree = _a.tree, _b = _a.context, context = _b === void 0 ? {} : _b, _c = _a.renderFunction, renderFunction = _c === void 0 ? require('react-dom/server').renderToStaticMarkup : _c; | ||
var renderPromises = new RenderPromises(); | ||
function process() { | ||
var ApolloContext = reactCommon.getApolloContext(); | ||
var html = renderFunction(React__default.createElement(ApolloContext.Provider, { value: tslib.__assign({}, context, { renderPromises: renderPromises }) }, tree)); | ||
return renderPromises.hasPromises() | ||
? renderPromises.consumeAndAwaitPromises().then(process) | ||
: html; | ||
} | ||
return Promise.resolve().then(process); | ||
var tree = _a.tree, | ||
_b = _a.context, | ||
context = _b === void 0 ? {} : _b, | ||
_c = _a.renderFunction, | ||
renderFunction = _c === void 0 ? require('react-dom/server').renderToStaticMarkup : _c; | ||
var renderPromises = new RenderPromises(); | ||
function process() { | ||
var ApolloContext = (0, _reactCommon.getApolloContext)(); | ||
var html = renderFunction(_react.default.createElement(ApolloContext.Provider, { | ||
value: (0, _tslib.__assign)({}, context, { | ||
renderPromises: renderPromises | ||
}) | ||
}, tree)); | ||
return renderPromises.hasPromises() ? renderPromises.consumeAndAwaitPromises().then(process) : html; | ||
} | ||
return Promise.resolve().then(process); | ||
} | ||
function renderToStringWithData(component) { | ||
return getMarkupFromTree({ | ||
tree: component, | ||
renderFunction: require('react-dom/server').renderToString | ||
}); | ||
return getMarkupFromTree({ | ||
tree: component, | ||
renderFunction: require('react-dom/server').renderToString | ||
}); | ||
} | ||
Object.defineProperty(exports, 'ApolloConsumer', { | ||
enumerable: true, | ||
get: function () { | ||
return reactCommon.ApolloConsumer; | ||
} | ||
}); | ||
Object.defineProperty(exports, 'ApolloProvider', { | ||
enumerable: true, | ||
get: function () { | ||
return reactCommon.ApolloProvider; | ||
} | ||
}); | ||
Object.defineProperty(exports, 'getApolloContext', { | ||
enumerable: true, | ||
get: function () { | ||
return reactCommon.getApolloContext; | ||
} | ||
}); | ||
Object.defineProperty(exports, 'resetApolloContext', { | ||
enumerable: true, | ||
get: function () { | ||
return reactCommon.resetApolloContext; | ||
} | ||
}); | ||
exports.getDataFromTree = getDataFromTree; | ||
exports.getMarkupFromTree = getMarkupFromTree; | ||
exports.renderToStringWithData = renderToStringWithData; | ||
exports.useApolloClient = useApolloClient; | ||
exports.useMutation = useMutation; | ||
exports.useQuery = useQuery; | ||
exports.useSubscription = useSubscription; |
@@ -6,117 +6,23 @@ import { parser, operationName, DocumentType, getApolloContext } from '@apollo/react-common'; | ||
import { NetworkStatus, ApolloError } from 'apollo-client'; | ||
import { isEqual } from 'apollo-utilities'; | ||
import { invariant } from 'ts-invariant'; | ||
import 'fast-json-stable-stringify'; | ||
/** | ||
* Copyright (c) Facebook, Inc. and its affiliates. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
* | ||
* | ||
*/ | ||
/** | ||
* Copyright (c) Facebook, Inc. and its affiliates. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
* | ||
* | ||
*/ | ||
function isEqual(a, b) { | ||
if (a === b) { | ||
return true; | ||
} | ||
if (a instanceof Date && b instanceof Date) { | ||
return a.getTime() === b.getTime(); | ||
} | ||
if (a != null && | ||
typeof a === 'object' && | ||
b != null && | ||
typeof b === 'object') { | ||
for (var key in a) { | ||
if (Object.prototype.hasOwnProperty.call(a, key)) { | ||
if (!Object.prototype.hasOwnProperty.call(b, key)) { | ||
return false; | ||
} | ||
if (!isEqual(a[key], b[key])) { | ||
return false; | ||
} | ||
} | ||
} | ||
for (var key in b) { | ||
if (Object.prototype.hasOwnProperty.call(b, key) && | ||
!Object.prototype.hasOwnProperty.call(a, key)) { | ||
return false; | ||
} | ||
} | ||
return true; | ||
} | ||
return false; | ||
} | ||
var OperationData = (function () { | ||
function OperationData(options, context) { | ||
this._isMounted = true; | ||
this._options = {}; | ||
this._previousOptions = {}; | ||
this._context = {}; | ||
this._options = options || {}; | ||
this._context = context || {}; | ||
this.isMounted = true; | ||
this.previousOptions = {}; | ||
this.context = {}; | ||
this.options = {}; | ||
this.options = options || {}; | ||
this.context = context || {}; | ||
} | ||
Object.defineProperty(OperationData.prototype, "isMounted", { | ||
get: function () { | ||
return this._isMounted; | ||
}, | ||
set: function (mounted) { | ||
this._isMounted = mounted; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(OperationData.prototype, "options", { | ||
get: function () { | ||
return this._options; | ||
}, | ||
set: function (newOptions) { | ||
if (!isEqual(this.options, newOptions)) { | ||
this.previousOptions = this.options; | ||
} | ||
this._options = newOptions; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(OperationData.prototype, "previousOptions", { | ||
get: function () { | ||
return this._previousOptions; | ||
}, | ||
set: function (newOptions) { | ||
this._previousOptions = newOptions; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(OperationData.prototype, "context", { | ||
get: function () { | ||
return this._context; | ||
}, | ||
set: function (newContext) { | ||
this._context = newContext; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(OperationData.prototype, "client", { | ||
get: function () { | ||
return this._client; | ||
}, | ||
set: function (newClient) { | ||
this._client = newClient; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
OperationData.prototype.getOptions = function () { | ||
return this.options; | ||
}; | ||
OperationData.prototype.setOptions = function (newOptions) { | ||
if (!isEqual(this.options, newOptions)) { | ||
this.previousOptions = this.options; | ||
} | ||
this.options = newOptions; | ||
}; | ||
OperationData.prototype.unmount = function () { | ||
@@ -128,3 +34,3 @@ this.isMounted = false; | ||
(this.context && this.context.client); | ||
process.env.NODE_ENV === "production" ? invariant(!!client) : invariant(!!client, 'Could not find "client" in the context or passed in as an option. ' + | ||
process.env.NODE_ENV === "production" ? invariant(!!client, 2) : invariant(!!client, 'Could not find "client" in the context or passed in as an option. ' + | ||
'Wrap the root component in an <ApolloProvider>, or pass an ' + | ||
@@ -147,3 +53,3 @@ 'ApolloClient instance in via options.'); | ||
var usedOperationName = operationName(operation.type); | ||
process.env.NODE_ENV === "production" ? invariant(operation.type === type) : invariant(operation.type === type, "Running a " + requiredOperationName + " requires a graphql " + | ||
process.env.NODE_ENV === "production" ? invariant(operation.type === type, 3) : invariant(operation.type === type, "Running a " + requiredOperationName + " requires a graphql " + | ||
(requiredOperationName + ", but a " + usedOperationName + " was used instead.")); | ||
@@ -167,3 +73,3 @@ }; | ||
this.refreshClient(); | ||
var _a = this.options, skip = _a.skip, query = _a.query; | ||
var _a = this.getOptions(), skip = _a.skip, query = _a.query; | ||
if (skip || query !== this.previousData.query) { | ||
@@ -185,5 +91,5 @@ this.removeQuerySubscription(); | ||
QueryData.prototype.fetchData = function () { | ||
if (this.options.skip) | ||
if (this.getOptions().skip) | ||
return false; | ||
var _a = this.options, children = _a.children, ssr = _a.ssr, displayName = _a.displayName, skip = _a.skip, onCompleted = _a.onCompleted, onError = _a.onError, partialRefetch = _a.partialRefetch, opts = __rest(_a, ["children", "ssr", "displayName", "skip", "onCompleted", "onError", "partialRefetch"]); | ||
var _a = this.getOptions(), children = _a.children, ssr = _a.ssr, displayName = _a.displayName, skip = _a.skip, onCompleted = _a.onCompleted, onError = _a.onError, partialRefetch = _a.partialRefetch, opts = __rest(_a, ["children", "ssr", "displayName", "skip", "onCompleted", "onError", "partialRefetch"]); | ||
var fetchPolicy = opts.fetchPolicy; | ||
@@ -197,3 +103,3 @@ if (ssr === false) | ||
if (this.context && this.context.renderPromises) { | ||
this.context.renderPromises.registerSSRObservable(obs, this.options); | ||
this.context.renderPromises.registerSSRObservable(obs, this.getOptions()); | ||
} | ||
@@ -219,8 +125,8 @@ var result = this.currentObservable.query.getCurrentResult(); | ||
QueryData.prototype.prepareObservableQueryOptions = function () { | ||
this.verifyDocumentType(this.options.query, DocumentType.Query); | ||
var displayName = this.options.displayName || 'Query'; | ||
return __assign({}, this.options, { displayName: displayName, context: this.options.context || {}, metadata: { reactComponent: { displayName: displayName } } }); | ||
this.verifyDocumentType(this.getOptions().query, DocumentType.Query); | ||
var displayName = this.getOptions().displayName || 'Query'; | ||
return __assign({}, this.getOptions(), { displayName: displayName, context: this.getOptions().context || {}, metadata: { reactComponent: { displayName: displayName } } }); | ||
}; | ||
QueryData.prototype.observableQueryFields = function (observable) { | ||
var fields = { | ||
return { | ||
variables: observable.variables, | ||
@@ -234,7 +140,6 @@ refetch: observable.refetch.bind(observable), | ||
}; | ||
return fields; | ||
}; | ||
QueryData.prototype.initializeObservableQuery = function () { | ||
if (this.context && this.context.renderPromises) { | ||
this.currentObservable.query = this.context.renderPromises.getSSRObservable(this.options); | ||
this.currentObservable.query = this.context.renderPromises.getSSRObservable(this.getOptions()); | ||
} | ||
@@ -256,3 +161,3 @@ if (!this.currentObservable.query) { | ||
.query.setOptions(newObservableQueryOptions) | ||
.catch(function () { return null; }); | ||
.catch(function () { }); | ||
} | ||
@@ -303,3 +208,3 @@ }; | ||
Object.assign(result, this.observableQueryFields(this.currentObservable.query)); | ||
if (this.options.skip) { | ||
if (this.getOptions().skip) { | ||
result = __assign({}, result, { data: undefined, error: undefined, loading: false }); | ||
@@ -330,3 +235,3 @@ } | ||
var fetchPolicy = this.currentObservable.query.options.fetchPolicy; | ||
var partialRefetch = this.options.partialRefetch; | ||
var partialRefetch = this.getOptions().partialRefetch; | ||
if (partialRefetch && | ||
@@ -355,7 +260,7 @@ Object.keys(data).length === 0 && | ||
if (!loading) { | ||
var _b = this.options, query = _b.query, variables = _b.variables, onCompleted = _b.onCompleted, onError = _b.onError; | ||
var _b = this.getOptions(), query = _b.query, variables = _b.variables, onCompleted = _b.onCompleted, onError = _b.onError; | ||
if (this.previousOptions && | ||
!this.previousData.loading && | ||
isEqual(this.previousOptions.query, query) && | ||
isEqual(this.previousOptions.variables, variables) && | ||
!this.previousData.loading) { | ||
isEqual(this.previousOptions.variables, variables)) { | ||
return; | ||
@@ -396,7 +301,5 @@ } | ||
var queryData = getQueryDataRef(); | ||
queryData.options = updatedOptions; | ||
queryData.setOptions(updatedOptions); | ||
queryData.context = context; | ||
useEffect(function () { | ||
return queryData.afterExecute(); | ||
}); | ||
useEffect(function () { return queryData.afterExecute(); }); | ||
return queryData.execute(); | ||
@@ -418,3 +321,3 @@ } | ||
var _this = this; | ||
this.verifyDocumentType(this.options.mutation, DocumentType.Mutation); | ||
this.verifyDocumentType(this.getOptions().mutation, DocumentType.Mutation); | ||
var runMutation = function (options) { return _this.runMutation(options); }; | ||
@@ -441,3 +344,3 @@ return [runMutation, result]; | ||
_this.onMutationError(error, mutationId); | ||
if (!_this.options.onError) | ||
if (!_this.getOptions().onError) | ||
throw error; | ||
@@ -447,15 +350,12 @@ }); | ||
MutationData.prototype.mutate = function (mutationFunctionOptions) { | ||
var _a = this.options, mutation = _a.mutation, variables = _a.variables, optimisticResponse = _a.optimisticResponse, update = _a.update, _b = _a.context, mutationContext = _b === void 0 ? {} : _b, _c = _a.awaitRefetchQueries, awaitRefetchQueries = _c === void 0 ? false : _c, fetchPolicy = _a.fetchPolicy; | ||
var _a = this.getOptions(), mutation = _a.mutation, variables = _a.variables, optimisticResponse = _a.optimisticResponse, update = _a.update, _b = _a.context, mutationContext = _b === void 0 ? {} : _b, _c = _a.awaitRefetchQueries, awaitRefetchQueries = _c === void 0 ? false : _c, fetchPolicy = _a.fetchPolicy; | ||
var mutateOptions = __assign({}, mutationFunctionOptions); | ||
var refetchQueries = mutateOptions.refetchQueries || this.options.refetchQueries; | ||
var mutateVariables = Object.assign({}, variables, mutateOptions.variables); | ||
delete mutateOptions.variables; | ||
return this.refreshClient().client.mutate(__assign({ mutation: mutation, | ||
optimisticResponse: optimisticResponse, | ||
refetchQueries: refetchQueries, | ||
awaitRefetchQueries: awaitRefetchQueries, | ||
optimisticResponse: optimisticResponse, refetchQueries: mutateOptions.refetchQueries || this.getOptions().refetchQueries, awaitRefetchQueries: awaitRefetchQueries, | ||
update: update, context: mutationContext, fetchPolicy: fetchPolicy, variables: mutateVariables }, mutateOptions)); | ||
}; | ||
MutationData.prototype.onMutationStart = function () { | ||
if (!this.result.loading && !this.options.ignoreResults) { | ||
if (!this.result.loading && !this.getOptions().ignoreResults) { | ||
this.updateResult({ | ||
@@ -470,3 +370,3 @@ loading: true, | ||
MutationData.prototype.onMutationCompleted = function (response, mutationId) { | ||
var _a = this.options, onCompleted = _a.onCompleted, ignoreResults = _a.ignoreResults; | ||
var _a = this.getOptions(), onCompleted = _a.onCompleted, ignoreResults = _a.ignoreResults; | ||
var data = response.data, errors = response.errors; | ||
@@ -490,4 +390,3 @@ var error = errors && errors.length > 0 | ||
MutationData.prototype.onMutationError = function (error, mutationId) { | ||
var onError = this.options.onError; | ||
var callOnError = function () { return (onError ? onError(error) : null); }; | ||
var onError = this.getOptions().onError; | ||
if (this.isMostRecentMutation(mutationId)) { | ||
@@ -501,7 +400,8 @@ this.updateResult({ | ||
} | ||
callOnError(); | ||
if (onError) { | ||
onError(error); | ||
} | ||
}; | ||
MutationData.prototype.generateNewMutationId = function () { | ||
this.mostRecentMutationId += 1; | ||
return this.mostRecentMutationId; | ||
return ++this.mostRecentMutationId; | ||
}; | ||
@@ -538,7 +438,5 @@ MutationData.prototype.isMostRecentMutation = function (mutationId) { | ||
var mutationData = getMutationDataRef(); | ||
mutationData.options = updatedOptions; | ||
mutationData.setOptions(updatedOptions); | ||
mutationData.context = context; | ||
useEffect(function () { | ||
return mutationData.afterExecute(); | ||
}); | ||
useEffect(function () { return mutationData.afterExecute(); }); | ||
return mutationData.execute(result); | ||
@@ -562,5 +460,5 @@ } | ||
} | ||
var shouldResubscribe = this.options.shouldResubscribe; | ||
var shouldResubscribe = this.getOptions().shouldResubscribe; | ||
if (typeof shouldResubscribe === 'function') { | ||
shouldResubscribe = !!shouldResubscribe(this.options); | ||
shouldResubscribe = !!shouldResubscribe(this.getOptions()); | ||
} | ||
@@ -570,4 +468,4 @@ if (shouldResubscribe !== false && | ||
Object.keys(this.previousOptions).length > 0 && | ||
(!isEqual(this.previousOptions.variables, this.options.variables) || | ||
this.previousOptions.subscription !== this.options.subscription)) { | ||
(this.previousOptions.subscription !== this.getOptions().subscription || | ||
!isEqual(this.previousOptions.variables, this.getOptions().variables))) { | ||
this.endSubscription(); | ||
@@ -577,6 +475,6 @@ delete this.currentObservable.query; | ||
} | ||
this.initialize(this.options); | ||
this.initialize(this.getOptions()); | ||
this.startSubscription(); | ||
this.previousOptions = this.options; | ||
return __assign({}, currentResult, { variables: this.options.variables }); | ||
this.previousOptions = this.getOptions(); | ||
return __assign({}, currentResult, { variables: this.getOptions().variables }); | ||
}; | ||
@@ -622,3 +520,3 @@ SubscriptionData.prototype.afterExecute = function () { | ||
SubscriptionData.prototype.updateCurrentData = function (result) { | ||
var onSubscriptionData = this.options.onSubscriptionData; | ||
var onSubscriptionData = this.getOptions().onSubscriptionData; | ||
if (onSubscriptionData) { | ||
@@ -643,3 +541,3 @@ onSubscriptionData({ | ||
SubscriptionData.prototype.completeSubscription = function () { | ||
var onSubscriptionComplete = this.options.onSubscriptionComplete; | ||
var onSubscriptionComplete = this.getOptions().onSubscriptionComplete; | ||
if (onSubscriptionComplete) | ||
@@ -679,7 +577,5 @@ onSubscriptionComplete(); | ||
var subscriptionData = getSubscriptionDataRef(); | ||
subscriptionData.options = updatedOptions; | ||
subscriptionData.setOptions(updatedOptions); | ||
subscriptionData.context = context; | ||
useEffect(function () { | ||
return subscriptionData.afterExecute(); | ||
}); | ||
useEffect(function () { return subscriptionData.afterExecute(); }); | ||
return subscriptionData.execute(result); | ||
@@ -690,3 +586,3 @@ } | ||
var client = React.useContext(getApolloContext()).client; | ||
process.env.NODE_ENV === "production" ? invariant(client) : invariant(client, 'No Apollo Client instance can be found. Please ensure that you ' + | ||
process.env.NODE_ENV === "production" ? invariant(client, 1) : invariant(client, 'No Apollo Client instance can be found. Please ensure that you ' + | ||
'have called `ApolloProvider` higher up in your tree.'); | ||
@@ -714,5 +610,5 @@ return client; | ||
RenderPromises.prototype.addQueryPromise = function (queryInstance, finish) { | ||
var info = this.lookupQueryInfo(queryInstance.options); | ||
var info = this.lookupQueryInfo(queryInstance.getOptions()); | ||
if (!info.seen) { | ||
this.queryPromises.set(queryInstance.options, new Promise(function (resolve) { | ||
this.queryPromises.set(queryInstance.getOptions(), new Promise(function (resolve) { | ||
resolve(queryInstance.fetchData()); | ||
@@ -719,0 +615,0 @@ })); |
(function (global, factory) { | ||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@apollo/react-common'), require('tslib'), require('react'), require('apollo-client'), require('ts-invariant'), require('fast-json-stable-stringify')) : | ||
typeof define === 'function' && define.amd ? define(['exports', '@apollo/react-common', 'tslib', 'react', 'apollo-client', 'ts-invariant', 'fast-json-stable-stringify'], factory) : | ||
(global = global || self, factory(global['react-hooks'] = {}, global.apolloReactCommon, global.tslib, global.React, global.apollo.core, global.invariant)); | ||
}(this, function (exports, reactCommon, tslib, React, apolloClient, tsInvariant) { 'use strict'; | ||
if (typeof define === "function" && define.amd) { | ||
define(["exports", "@apollo/react-common", "tslib", "react", "apollo-client", "apollo-utilities", "ts-invariant"], factory); | ||
} else if (typeof exports !== "undefined") { | ||
factory(exports, require("@apollo/react-common"), require("tslib"), require("react"), require("apollo-client"), require("apollo-utilities"), require("ts-invariant")); | ||
} else { | ||
var mod = { | ||
exports: {} | ||
}; | ||
factory(mod.exports, global.reactCommon, global.tslib, global.react, global.apolloClient, global.apolloUtilities, global.tsInvariant); | ||
global.unknown = mod.exports; | ||
} | ||
})(this, function (_exports, _reactCommon, _tslib, _react, _apolloClient, _apolloUtilities, _tsInvariant) { | ||
var React__default = 'default' in React ? React['default'] : React; | ||
_exports.__esModule = true; | ||
_exports.getDataFromTree = getDataFromTree; | ||
_exports.getMarkupFromTree = getMarkupFromTree; | ||
_exports.renderToStringWithData = renderToStringWithData; | ||
_exports.useApolloClient = useApolloClient; | ||
_exports.useMutation = useMutation; | ||
_exports.useQuery = useQuery; | ||
_exports.useSubscription = useSubscription; | ||
_exports.resetApolloContext = _exports.ApolloProvider = _exports.ApolloConsumer = void 0; | ||
_exports.getApolloContext = _reactCommon.getApolloContext; | ||
_exports.ApolloConsumer = _reactCommon.ApolloConsumer; | ||
_exports.ApolloProvider = _reactCommon.ApolloProvider; | ||
_exports.resetApolloContext = _reactCommon.resetApolloContext; | ||
_react = _interopRequireWildcard(_react); | ||
/** | ||
* Copyright (c) Facebook, Inc. and its affiliates. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
* | ||
* | ||
*/ | ||
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {}; if (desc.get || desc.set) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; return newObj; } } | ||
/** | ||
* Copyright (c) Facebook, Inc. and its affiliates. | ||
* | ||
* This source code is licensed under the MIT license found in the | ||
* LICENSE file in the root directory of this source tree. | ||
* | ||
* | ||
*/ | ||
var OperationData = function () { | ||
function OperationData(options, context) { | ||
this.isMounted = true; | ||
this.previousOptions = {}; | ||
this.context = {}; | ||
this.options = {}; | ||
this.options = options || {}; | ||
this.context = context || {}; | ||
} | ||
function isEqual(a, b) { | ||
if (a === b) { | ||
return true; | ||
} | ||
if (a instanceof Date && b instanceof Date) { | ||
return a.getTime() === b.getTime(); | ||
} | ||
if (a != null && | ||
typeof a === 'object' && | ||
b != null && | ||
typeof b === 'object') { | ||
for (var key in a) { | ||
if (Object.prototype.hasOwnProperty.call(a, key)) { | ||
if (!Object.prototype.hasOwnProperty.call(b, key)) { | ||
return false; | ||
} | ||
if (!isEqual(a[key], b[key])) { | ||
return false; | ||
} | ||
} | ||
} | ||
for (var key in b) { | ||
if (Object.prototype.hasOwnProperty.call(b, key) && | ||
!Object.prototype.hasOwnProperty.call(a, key)) { | ||
return false; | ||
} | ||
} | ||
return true; | ||
} | ||
return false; | ||
OperationData.prototype.getOptions = function () { | ||
return this.options; | ||
}; | ||
OperationData.prototype.setOptions = function (newOptions) { | ||
if (!(0, _apolloUtilities.isEqual)(this.options, newOptions)) { | ||
this.previousOptions = this.options; | ||
} | ||
this.options = newOptions; | ||
}; | ||
OperationData.prototype.unmount = function () { | ||
this.isMounted = false; | ||
}; | ||
OperationData.prototype.refreshClient = function () { | ||
var client = this.options && this.options.client || this.context && this.context.client; | ||
process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(!!client, 2) : (0, _tsInvariant.invariant)(!!client, 'Could not find "client" in the context or passed in as an option. ' + 'Wrap the root component in an <ApolloProvider>, or pass an ' + 'ApolloClient instance in via options.'); | ||
var isNew = false; | ||
if (client !== this.client) { | ||
isNew = true; | ||
this.client = client; | ||
this.cleanup(); | ||
} | ||
return { | ||
client: this.client, | ||
isNew: isNew | ||
}; | ||
}; | ||
OperationData.prototype.verifyDocumentType = function (document, type) { | ||
var operation = (0, _reactCommon.parser)(document); | ||
var requiredOperationName = (0, _reactCommon.operationName)(type); | ||
var usedOperationName = (0, _reactCommon.operationName)(operation.type); | ||
process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(operation.type === type, 3) : (0, _tsInvariant.invariant)(operation.type === type, "Running a " + requiredOperationName + " requires a graphql " + (requiredOperationName + ", but a " + usedOperationName + " was used instead.")); | ||
}; | ||
return OperationData; | ||
}(); | ||
var QueryData = function (_super) { | ||
(0, _tslib.__extends)(QueryData, _super); | ||
function QueryData(_a) { | ||
var options = _a.options, | ||
context = _a.context, | ||
forceUpdate = _a.forceUpdate; | ||
var _this = _super.call(this, options, context) || this; | ||
_this.previousData = {}; | ||
_this.currentObservable = {}; | ||
_this.forceUpdate = forceUpdate; | ||
return _this; | ||
} | ||
var OperationData = (function () { | ||
function OperationData(options, context) { | ||
this._isMounted = true; | ||
this._options = {}; | ||
this._previousOptions = {}; | ||
this._context = {}; | ||
this._options = options || {}; | ||
this._context = context || {}; | ||
QueryData.prototype.execute = function () { | ||
var _this = this; | ||
this.refreshClient(); | ||
var _a = this.getOptions(), | ||
skip = _a.skip, | ||
query = _a.query; | ||
if (skip || query !== this.previousData.query) { | ||
this.removeQuerySubscription(); | ||
this.previousData.query = query; | ||
} | ||
this.updateObservableQuery(); | ||
if (!skip) { | ||
this.startQuerySubscription(); | ||
} | ||
var finish = function () { | ||
return _this.getQueryResult(); | ||
}; | ||
if (this.context && this.context.renderPromises) { | ||
var result = this.context.renderPromises.addQueryPromise(this, finish); | ||
return result || { | ||
loading: true, | ||
networkStatus: _apolloClient.NetworkStatus.loading | ||
}; | ||
} | ||
return finish(); | ||
}; | ||
QueryData.prototype.fetchData = function () { | ||
if (this.getOptions().skip) return false; | ||
var _a = this.getOptions(), | ||
children = _a.children, | ||
ssr = _a.ssr, | ||
displayName = _a.displayName, | ||
skip = _a.skip, | ||
onCompleted = _a.onCompleted, | ||
onError = _a.onError, | ||
partialRefetch = _a.partialRefetch, | ||
opts = (0, _tslib.__rest)(_a, ["children", "ssr", "displayName", "skip", "onCompleted", "onError", "partialRefetch"]); | ||
var fetchPolicy = opts.fetchPolicy; | ||
if (ssr === false) return false; | ||
if (fetchPolicy === 'network-only' || fetchPolicy === 'cache-and-network') { | ||
fetchPolicy = 'cache-first'; | ||
} | ||
var obs = this.refreshClient().client.watchQuery((0, _tslib.__assign)({}, opts, { | ||
fetchPolicy: fetchPolicy | ||
})); | ||
if (this.context && this.context.renderPromises) { | ||
this.context.renderPromises.registerSSRObservable(obs, this.getOptions()); | ||
} | ||
var result = this.currentObservable.query.getCurrentResult(); | ||
return result.loading ? obs.result() : false; | ||
}; | ||
QueryData.prototype.afterExecute = function () { | ||
this.isMounted = true; | ||
this.handleErrorOrCompleted(); | ||
return this.unmount.bind(this); | ||
}; | ||
QueryData.prototype.cleanup = function () { | ||
this.removeQuerySubscription(); | ||
this.currentObservable.query = null; | ||
this.previousData.result = null; | ||
}; | ||
QueryData.prototype.updateCurrentData = function () { | ||
if (this.isMounted) { | ||
this.forceUpdate(); | ||
} | ||
}; | ||
QueryData.prototype.prepareObservableQueryOptions = function () { | ||
this.verifyDocumentType(this.getOptions().query, _reactCommon.DocumentType.Query); | ||
var displayName = this.getOptions().displayName || 'Query'; | ||
return (0, _tslib.__assign)({}, this.getOptions(), { | ||
displayName: displayName, | ||
context: this.getOptions().context || {}, | ||
metadata: { | ||
reactComponent: { | ||
displayName: displayName | ||
} | ||
} | ||
Object.defineProperty(OperationData.prototype, "isMounted", { | ||
get: function () { | ||
return this._isMounted; | ||
}, | ||
set: function (mounted) { | ||
this._isMounted = mounted; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
}; | ||
QueryData.prototype.observableQueryFields = function (observable) { | ||
return { | ||
variables: observable.variables, | ||
refetch: observable.refetch.bind(observable), | ||
fetchMore: observable.fetchMore.bind(observable), | ||
updateQuery: observable.updateQuery.bind(observable), | ||
startPolling: observable.startPolling.bind(observable), | ||
stopPolling: observable.stopPolling.bind(observable), | ||
subscribeToMore: observable.subscribeToMore.bind(observable) | ||
}; | ||
}; | ||
QueryData.prototype.initializeObservableQuery = function () { | ||
if (this.context && this.context.renderPromises) { | ||
this.currentObservable.query = this.context.renderPromises.getSSRObservable(this.getOptions()); | ||
} | ||
if (!this.currentObservable.query) { | ||
var observableQueryOptions = this.prepareObservableQueryOptions(); | ||
this.previousData.observableQueryOptions = (0, _tslib.__assign)({}, observableQueryOptions, { | ||
children: null | ||
}); | ||
Object.defineProperty(OperationData.prototype, "options", { | ||
get: function () { | ||
return this._options; | ||
}, | ||
set: function (newOptions) { | ||
if (!isEqual(this.options, newOptions)) { | ||
this.previousOptions = this.options; | ||
} | ||
this._options = newOptions; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
this.currentObservable.query = this.refreshClient().client.watchQuery(observableQueryOptions); | ||
} | ||
}; | ||
QueryData.prototype.updateObservableQuery = function () { | ||
if (!this.currentObservable.query) { | ||
this.initializeObservableQuery(); | ||
} | ||
var newObservableQueryOptions = (0, _tslib.__assign)({}, this.prepareObservableQueryOptions(), { | ||
children: null | ||
}); | ||
if (!(0, _apolloUtilities.isEqual)(newObservableQueryOptions, this.previousData.observableQueryOptions)) { | ||
this.previousData.observableQueryOptions = newObservableQueryOptions; | ||
this.currentObservable.query.setOptions(newObservableQueryOptions).catch(function () {}); | ||
} | ||
}; | ||
QueryData.prototype.startQuerySubscription = function () { | ||
var _this = this; | ||
if (this.currentObservable.subscription) return; | ||
var obsQuery = this.currentObservable.query; | ||
this.currentObservable.subscription = obsQuery.subscribe({ | ||
next: function (_a) { | ||
var loading = _a.loading, | ||
networkStatus = _a.networkStatus, | ||
data = _a.data; | ||
if (_this.previousData.result && _this.previousData.result.loading === loading && _this.previousData.result.networkStatus === networkStatus && (0, _apolloUtilities.isEqual)(_this.previousData.result.data, data || {})) { | ||
return; | ||
} | ||
_this.updateCurrentData(); | ||
}, | ||
error: function (error) { | ||
if (!_this.previousData.result || _this.previousData.result.networkStatus === _apolloClient.NetworkStatus.refetch) { | ||
_this.resubscribeToQuery(); | ||
} | ||
if (!error.hasOwnProperty('graphQLErrors')) throw error; | ||
_this.updateCurrentData(); | ||
} | ||
}); | ||
}; | ||
QueryData.prototype.resubscribeToQuery = function () { | ||
this.removeQuerySubscription(); | ||
var lastError = this.currentObservable.query.getLastError(); | ||
var lastResult = this.currentObservable.query.getLastResult(); | ||
this.currentObservable.query.resetLastResults(); | ||
this.startQuerySubscription(); | ||
Object.assign(this.currentObservable.query, { | ||
lastError: lastError, | ||
lastResult: lastResult | ||
}); | ||
}; | ||
QueryData.prototype.getQueryResult = function () { | ||
var result = { | ||
data: Object.create(null) | ||
}; | ||
Object.assign(result, this.observableQueryFields(this.currentObservable.query)); | ||
if (this.getOptions().skip) { | ||
result = (0, _tslib.__assign)({}, result, { | ||
data: undefined, | ||
error: undefined, | ||
loading: false | ||
}); | ||
Object.defineProperty(OperationData.prototype, "previousOptions", { | ||
get: function () { | ||
return this._previousOptions; | ||
}, | ||
set: function (newOptions) { | ||
this._previousOptions = newOptions; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
} else { | ||
var currentResult = this.currentObservable.query.getCurrentResult(); | ||
var loading = currentResult.loading, | ||
partial = currentResult.partial, | ||
networkStatus = currentResult.networkStatus, | ||
errors = currentResult.errors; | ||
var error = currentResult.error, | ||
data = currentResult.data; | ||
data = data || Object.create(null); | ||
if (errors && errors.length > 0) { | ||
error = new _apolloClient.ApolloError({ | ||
graphQLErrors: errors | ||
}); | ||
} | ||
Object.assign(result, { | ||
loading: loading, | ||
networkStatus: networkStatus, | ||
error: error | ||
}); | ||
Object.defineProperty(OperationData.prototype, "context", { | ||
get: function () { | ||
return this._context; | ||
}, | ||
set: function (newContext) { | ||
this._context = newContext; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
Object.defineProperty(OperationData.prototype, "client", { | ||
get: function () { | ||
return this._client; | ||
}, | ||
set: function (newClient) { | ||
this._client = newClient; | ||
}, | ||
enumerable: true, | ||
configurable: true | ||
}); | ||
OperationData.prototype.unmount = function () { | ||
this.isMounted = false; | ||
}; | ||
OperationData.prototype.refreshClient = function () { | ||
var client = (this.options && this.options.client) || | ||
(this.context && this.context.client); | ||
process.env.NODE_ENV === "production" ? tsInvariant.invariant(!!client) : tsInvariant.invariant(!!client, 'Could not find "client" in the context or passed in as an option. ' + | ||
'Wrap the root component in an <ApolloProvider>, or pass an ' + | ||
'ApolloClient instance in via options.'); | ||
var isNew = false; | ||
if (client !== this.client) { | ||
isNew = true; | ||
this.client = client; | ||
this.cleanup(); | ||
} | ||
return { | ||
client: this.client, | ||
isNew: isNew | ||
}; | ||
}; | ||
OperationData.prototype.verifyDocumentType = function (document, type) { | ||
var operation = reactCommon.parser(document); | ||
var requiredOperationName = reactCommon.operationName(type); | ||
var usedOperationName = reactCommon.operationName(operation.type); | ||
process.env.NODE_ENV === "production" ? tsInvariant.invariant(operation.type === type) : tsInvariant.invariant(operation.type === type, "Running a " + requiredOperationName + " requires a graphql " + | ||
(requiredOperationName + ", but a " + usedOperationName + " was used instead.")); | ||
}; | ||
return OperationData; | ||
}()); | ||
var QueryData = (function (_super) { | ||
tslib.__extends(QueryData, _super); | ||
function QueryData(_a) { | ||
var options = _a.options, context = _a.context, forceUpdate = _a.forceUpdate; | ||
var _this = _super.call(this, options, context) || this; | ||
_this.previousData = {}; | ||
_this.currentObservable = {}; | ||
_this.forceUpdate = forceUpdate; | ||
return _this; | ||
} | ||
QueryData.prototype.execute = function () { | ||
var _this = this; | ||
this.refreshClient(); | ||
var _a = this.options, skip = _a.skip, query = _a.query; | ||
if (skip || query !== this.previousData.query) { | ||
this.removeQuerySubscription(); | ||
this.previousData.query = query; | ||
} | ||
this.updateObservableQuery(); | ||
if (!skip) { | ||
this.startQuerySubscription(); | ||
} | ||
var finish = function () { return _this.getQueryResult(); }; | ||
if (this.context && this.context.renderPromises) { | ||
var result = this.context.renderPromises.addQueryPromise(this, finish); | ||
return result || { loading: true, networkStatus: apolloClient.NetworkStatus.loading }; | ||
} | ||
return finish(); | ||
}; | ||
QueryData.prototype.fetchData = function () { | ||
if (this.options.skip) | ||
return false; | ||
var _a = this.options, children = _a.children, ssr = _a.ssr, displayName = _a.displayName, skip = _a.skip, onCompleted = _a.onCompleted, onError = _a.onError, partialRefetch = _a.partialRefetch, opts = tslib.__rest(_a, ["children", "ssr", "displayName", "skip", "onCompleted", "onError", "partialRefetch"]); | ||
var fetchPolicy = opts.fetchPolicy; | ||
if (ssr === false) | ||
return false; | ||
if (fetchPolicy === 'network-only' || fetchPolicy === 'cache-and-network') { | ||
fetchPolicy = 'cache-first'; | ||
} | ||
var obs = this.refreshClient().client.watchQuery(tslib.__assign({}, opts, { fetchPolicy: fetchPolicy })); | ||
if (this.context && this.context.renderPromises) { | ||
this.context.renderPromises.registerSSRObservable(obs, this.options); | ||
} | ||
var result = this.currentObservable.query.getCurrentResult(); | ||
return result.loading ? obs.result() : false; | ||
}; | ||
QueryData.prototype.afterExecute = function () { | ||
this.isMounted = true; | ||
this.handleErrorOrCompleted(); | ||
return this.unmount.bind(this); | ||
}; | ||
QueryData.prototype.cleanup = function () { | ||
this.removeQuerySubscription(); | ||
this.currentObservable.query = null; | ||
this.previousData.result = null; | ||
}; | ||
QueryData.prototype.updateCurrentData = function () { | ||
if (this.isMounted) { | ||
this.forceUpdate(); | ||
} | ||
}; | ||
QueryData.prototype.prepareObservableQueryOptions = function () { | ||
this.verifyDocumentType(this.options.query, reactCommon.DocumentType.Query); | ||
var displayName = this.options.displayName || 'Query'; | ||
return tslib.__assign({}, this.options, { displayName: displayName, context: this.options.context || {}, metadata: { reactComponent: { displayName: displayName } } }); | ||
}; | ||
QueryData.prototype.observableQueryFields = function (observable) { | ||
var fields = { | ||
variables: observable.variables, | ||
refetch: observable.refetch.bind(observable), | ||
fetchMore: observable.fetchMore.bind(observable), | ||
updateQuery: observable.updateQuery.bind(observable), | ||
startPolling: observable.startPolling.bind(observable), | ||
stopPolling: observable.stopPolling.bind(observable), | ||
subscribeToMore: observable.subscribeToMore.bind(observable) | ||
}; | ||
return fields; | ||
}; | ||
QueryData.prototype.initializeObservableQuery = function () { | ||
if (this.context && this.context.renderPromises) { | ||
this.currentObservable.query = this.context.renderPromises.getSSRObservable(this.options); | ||
} | ||
if (!this.currentObservable.query) { | ||
var observableQueryOptions = this.prepareObservableQueryOptions(); | ||
this.previousData.observableQueryOptions = tslib.__assign({}, observableQueryOptions, { children: null }); | ||
this.currentObservable.query = this.refreshClient().client.watchQuery(observableQueryOptions); | ||
} | ||
}; | ||
QueryData.prototype.updateObservableQuery = function () { | ||
if (!this.currentObservable.query) { | ||
this.initializeObservableQuery(); | ||
} | ||
var newObservableQueryOptions = tslib.__assign({}, this.prepareObservableQueryOptions(), { children: null }); | ||
if (!isEqual(newObservableQueryOptions, this.previousData.observableQueryOptions)) { | ||
this.previousData.observableQueryOptions = newObservableQueryOptions; | ||
this.currentObservable | ||
.query.setOptions(newObservableQueryOptions) | ||
.catch(function () { return null; }); | ||
} | ||
}; | ||
QueryData.prototype.startQuerySubscription = function () { | ||
var _this = this; | ||
if (this.currentObservable.subscription) | ||
return; | ||
var obsQuery = this.currentObservable.query; | ||
this.currentObservable.subscription = obsQuery.subscribe({ | ||
next: function (_a) { | ||
var loading = _a.loading, networkStatus = _a.networkStatus, data = _a.data; | ||
if (_this.previousData.result && | ||
_this.previousData.result.loading === loading && | ||
_this.previousData.result.networkStatus === networkStatus && | ||
isEqual(_this.previousData.result.data, data || {})) { | ||
return; | ||
} | ||
_this.updateCurrentData(); | ||
}, | ||
error: function (error) { | ||
if (!_this.previousData.result || | ||
_this.previousData.result.networkStatus === apolloClient.NetworkStatus.refetch) { | ||
_this.resubscribeToQuery(); | ||
} | ||
if (!error.hasOwnProperty('graphQLErrors')) | ||
throw error; | ||
_this.updateCurrentData(); | ||
} | ||
if (loading) { | ||
var previousData = this.previousData.result ? this.previousData.result.data : {}; | ||
Object.assign(result.data, previousData, data); | ||
} else if (error) { | ||
Object.assign(result, { | ||
data: (this.currentObservable.query.getLastResult() || {}).data | ||
}); | ||
} else { | ||
var fetchPolicy = this.currentObservable.query.options.fetchPolicy; | ||
var partialRefetch = this.getOptions().partialRefetch; | ||
if (partialRefetch && Object.keys(data).length === 0 && partial && fetchPolicy !== 'cache-only') { | ||
Object.assign(result, { | ||
loading: true, | ||
networkStatus: _apolloClient.NetworkStatus.loading | ||
}); | ||
}; | ||
QueryData.prototype.resubscribeToQuery = function () { | ||
this.removeQuerySubscription(); | ||
var lastError = this.currentObservable.query.getLastError(); | ||
var lastResult = this.currentObservable.query.getLastResult(); | ||
this.currentObservable.query.resetLastResults(); | ||
this.startQuerySubscription(); | ||
Object.assign(this.currentObservable.query, { | ||
lastError: lastError, | ||
lastResult: lastResult | ||
}); | ||
}; | ||
QueryData.prototype.getQueryResult = function () { | ||
var result = { | ||
data: Object.create(null) | ||
}; | ||
Object.assign(result, this.observableQueryFields(this.currentObservable.query)); | ||
if (this.options.skip) { | ||
result = tslib.__assign({}, result, { data: undefined, error: undefined, loading: false }); | ||
} | ||
else { | ||
var currentResult = this.currentObservable.query.getCurrentResult(); | ||
var loading = currentResult.loading, partial = currentResult.partial, networkStatus = currentResult.networkStatus, errors = currentResult.errors; | ||
var error = currentResult.error, data = currentResult.data; | ||
data = data || Object.create(null); | ||
if (errors && errors.length > 0) { | ||
error = new apolloClient.ApolloError({ graphQLErrors: errors }); | ||
} | ||
Object.assign(result, { loading: loading, networkStatus: networkStatus, error: error }); | ||
if (loading) { | ||
var previousData = this.previousData.result | ||
? this.previousData.result.data | ||
: {}; | ||
Object.assign(result.data, previousData, data); | ||
} | ||
else if (error) { | ||
Object.assign(result, { | ||
data: (this.currentObservable.query.getLastResult() || {}) | ||
.data | ||
}); | ||
} | ||
else { | ||
var fetchPolicy = this.currentObservable.query.options.fetchPolicy; | ||
var partialRefetch = this.options.partialRefetch; | ||
if (partialRefetch && | ||
Object.keys(data).length === 0 && | ||
partial && | ||
fetchPolicy !== 'cache-only') { | ||
Object.assign(result, { | ||
loading: true, | ||
networkStatus: apolloClient.NetworkStatus.loading | ||
}); | ||
result.refetch(); | ||
return result; | ||
} | ||
Object.assign(result.data, data); | ||
} | ||
} | ||
result.client = this.client; | ||
this.previousData.loading = | ||
(this.previousData.result && this.previousData.result.loading) || false; | ||
this.previousData.result = result; | ||
result.refetch(); | ||
return result; | ||
}; | ||
QueryData.prototype.handleErrorOrCompleted = function () { | ||
var _a = this.currentObservable.query.getCurrentResult(), data = _a.data, loading = _a.loading, error = _a.error; | ||
if (!loading) { | ||
var _b = this.options, query = _b.query, variables = _b.variables, onCompleted = _b.onCompleted, onError = _b.onError; | ||
if (this.previousOptions && | ||
isEqual(this.previousOptions.query, query) && | ||
isEqual(this.previousOptions.variables, variables) && | ||
!this.previousData.loading) { | ||
return; | ||
} | ||
if (onCompleted && !error) { | ||
onCompleted(data); | ||
} | ||
else if (onError && error) { | ||
onError(error); | ||
} | ||
} | ||
}; | ||
QueryData.prototype.removeQuerySubscription = function () { | ||
if (this.currentObservable.subscription) { | ||
this.currentObservable.subscription.unsubscribe(); | ||
delete this.currentObservable.subscription; | ||
} | ||
}; | ||
return QueryData; | ||
}(OperationData)); | ||
} | ||
function useQuery(query, options) { | ||
var context = React.useContext(reactCommon.getApolloContext()); | ||
var _a = React.useReducer(function (x) { return x + 1; }, 0), _ignored = _a[0], forceUpdate = _a[1]; | ||
var updatedOptions = options ? tslib.__assign({}, options, { query: query }) : { query: query }; | ||
var queryDataRef = React.useRef(); | ||
function getQueryDataRef() { | ||
if (!queryDataRef.current) { | ||
queryDataRef.current = new QueryData({ | ||
options: updatedOptions, | ||
context: context, | ||
forceUpdate: forceUpdate | ||
}); | ||
} | ||
return queryDataRef.current; | ||
Object.assign(result.data, data); | ||
} | ||
var queryData = getQueryDataRef(); | ||
queryData.options = updatedOptions; | ||
queryData.context = context; | ||
React.useEffect(function () { | ||
return queryData.afterExecute(); | ||
}); | ||
return queryData.execute(); | ||
} | ||
} | ||
var MutationData = (function (_super) { | ||
tslib.__extends(MutationData, _super); | ||
function MutationData(_a) { | ||
var options = _a.options, context = _a.context, result = _a.result, setResult = _a.setResult; | ||
var _this = _super.call(this, options, context) || this; | ||
_this.verifyDocumentType(options.mutation, reactCommon.DocumentType.Mutation); | ||
_this.result = result; | ||
_this.setResult = setResult; | ||
_this.mostRecentMutationId = 0; | ||
return _this; | ||
result.client = this.client; | ||
this.previousData.loading = this.previousData.result && this.previousData.result.loading || false; | ||
this.previousData.result = result; | ||
return result; | ||
}; | ||
QueryData.prototype.handleErrorOrCompleted = function () { | ||
var _a = this.currentObservable.query.getCurrentResult(), | ||
data = _a.data, | ||
loading = _a.loading, | ||
error = _a.error; | ||
if (!loading) { | ||
var _b = this.getOptions(), | ||
query = _b.query, | ||
variables = _b.variables, | ||
onCompleted = _b.onCompleted, | ||
onError = _b.onError; | ||
if (this.previousOptions && !this.previousData.loading && (0, _apolloUtilities.isEqual)(this.previousOptions.query, query) && (0, _apolloUtilities.isEqual)(this.previousOptions.variables, variables)) { | ||
return; | ||
} | ||
MutationData.prototype.execute = function (result) { | ||
var _this = this; | ||
this.verifyDocumentType(this.options.mutation, reactCommon.DocumentType.Mutation); | ||
var runMutation = function (options) { return _this.runMutation(options); }; | ||
return [runMutation, result]; | ||
}; | ||
MutationData.prototype.afterExecute = function () { | ||
this.isMounted = true; | ||
return this.unmount.bind(this); | ||
}; | ||
MutationData.prototype.cleanup = function () { | ||
}; | ||
MutationData.prototype.runMutation = function (mutationFunctionOptions) { | ||
var _this = this; | ||
if (mutationFunctionOptions === void 0) { mutationFunctionOptions = {}; } | ||
this.onMutationStart(); | ||
var mutationId = this.generateNewMutationId(); | ||
return this.mutate(mutationFunctionOptions) | ||
.then(function (response) { | ||
_this.onMutationCompleted(response, mutationId); | ||
return response; | ||
}) | ||
.catch(function (error) { | ||
_this.onMutationError(error, mutationId); | ||
if (!_this.options.onError) | ||
throw error; | ||
}); | ||
}; | ||
MutationData.prototype.mutate = function (mutationFunctionOptions) { | ||
var _a = this.options, mutation = _a.mutation, variables = _a.variables, optimisticResponse = _a.optimisticResponse, update = _a.update, _b = _a.context, mutationContext = _b === void 0 ? {} : _b, _c = _a.awaitRefetchQueries, awaitRefetchQueries = _c === void 0 ? false : _c, fetchPolicy = _a.fetchPolicy; | ||
var mutateOptions = tslib.__assign({}, mutationFunctionOptions); | ||
var refetchQueries = mutateOptions.refetchQueries || this.options.refetchQueries; | ||
var mutateVariables = Object.assign({}, variables, mutateOptions.variables); | ||
delete mutateOptions.variables; | ||
return this.refreshClient().client.mutate(tslib.__assign({ mutation: mutation, | ||
optimisticResponse: optimisticResponse, | ||
refetchQueries: refetchQueries, | ||
awaitRefetchQueries: awaitRefetchQueries, | ||
update: update, context: mutationContext, fetchPolicy: fetchPolicy, variables: mutateVariables }, mutateOptions)); | ||
}; | ||
MutationData.prototype.onMutationStart = function () { | ||
if (!this.result.loading && !this.options.ignoreResults) { | ||
this.updateResult({ | ||
loading: true, | ||
error: undefined, | ||
data: undefined, | ||
called: true | ||
}); | ||
} | ||
}; | ||
MutationData.prototype.onMutationCompleted = function (response, mutationId) { | ||
var _a = this.options, onCompleted = _a.onCompleted, ignoreResults = _a.ignoreResults; | ||
var data = response.data, errors = response.errors; | ||
var error = errors && errors.length > 0 | ||
? new apolloClient.ApolloError({ graphQLErrors: errors }) | ||
: undefined; | ||
var callOncomplete = function () { | ||
return onCompleted ? onCompleted(data) : null; | ||
}; | ||
if (this.isMostRecentMutation(mutationId) && !ignoreResults) { | ||
this.updateResult({ | ||
called: true, | ||
loading: false, | ||
data: data, | ||
error: error | ||
}); | ||
} | ||
callOncomplete(); | ||
}; | ||
MutationData.prototype.onMutationError = function (error, mutationId) { | ||
var onError = this.options.onError; | ||
var callOnError = function () { return (onError ? onError(error) : null); }; | ||
if (this.isMostRecentMutation(mutationId)) { | ||
this.updateResult({ | ||
loading: false, | ||
error: error, | ||
data: undefined, | ||
called: true | ||
}); | ||
} | ||
callOnError(); | ||
}; | ||
MutationData.prototype.generateNewMutationId = function () { | ||
this.mostRecentMutationId += 1; | ||
return this.mostRecentMutationId; | ||
}; | ||
MutationData.prototype.isMostRecentMutation = function (mutationId) { | ||
return this.mostRecentMutationId === mutationId; | ||
}; | ||
MutationData.prototype.updateResult = function (result) { | ||
if (this.isMounted && | ||
(!this.previousResult || !isEqual(this.previousResult, result))) { | ||
this.setResult(result); | ||
this.previousResult = result; | ||
} | ||
}; | ||
return MutationData; | ||
}(OperationData)); | ||
function useMutation(mutation, options) { | ||
var context = React.useContext(reactCommon.getApolloContext()); | ||
var _a = React.useState({ called: false, loading: false }), result = _a[0], setResult = _a[1]; | ||
var updatedOptions = options ? tslib.__assign({}, options, { mutation: mutation }) : { mutation: mutation }; | ||
var mutationDataRef = React.useRef(); | ||
function getMutationDataRef() { | ||
if (!mutationDataRef.current) { | ||
mutationDataRef.current = new MutationData({ | ||
options: updatedOptions, | ||
context: context, | ||
result: result, | ||
setResult: setResult | ||
}); | ||
} | ||
return mutationDataRef.current; | ||
if (onCompleted && !error) { | ||
onCompleted(data); | ||
} else if (onError && error) { | ||
onError(error); | ||
} | ||
var mutationData = getMutationDataRef(); | ||
mutationData.options = updatedOptions; | ||
mutationData.context = context; | ||
React.useEffect(function () { | ||
return mutationData.afterExecute(); | ||
} | ||
}; | ||
QueryData.prototype.removeQuerySubscription = function () { | ||
if (this.currentObservable.subscription) { | ||
this.currentObservable.subscription.unsubscribe(); | ||
delete this.currentObservable.subscription; | ||
} | ||
}; | ||
return QueryData; | ||
}(OperationData); | ||
function useQuery(query, options) { | ||
var context = (0, _react.useContext)((0, _reactCommon.getApolloContext)()); | ||
var _a = (0, _react.useReducer)(function (x) { | ||
return x + 1; | ||
}, 0), | ||
_ignored = _a[0], | ||
forceUpdate = _a[1]; | ||
var updatedOptions = options ? (0, _tslib.__assign)({}, options, { | ||
query: query | ||
}) : { | ||
query: query | ||
}; | ||
var queryDataRef = (0, _react.useRef)(); | ||
function getQueryDataRef() { | ||
if (!queryDataRef.current) { | ||
queryDataRef.current = new QueryData({ | ||
options: updatedOptions, | ||
context: context, | ||
forceUpdate: forceUpdate | ||
}); | ||
return mutationData.execute(result); | ||
} | ||
return queryDataRef.current; | ||
} | ||
var SubscriptionData = (function (_super) { | ||
tslib.__extends(SubscriptionData, _super); | ||
function SubscriptionData(_a) { | ||
var options = _a.options, context = _a.context, setResult = _a.setResult; | ||
var _this = _super.call(this, options, context) || this; | ||
_this.currentObservable = {}; | ||
_this.setResult = setResult; | ||
_this.initialize(options); | ||
return _this; | ||
} | ||
SubscriptionData.prototype.execute = function (result) { | ||
var currentResult = result; | ||
if (this.refreshClient().isNew) { | ||
currentResult = this.getLoadingResult(); | ||
} | ||
var shouldResubscribe = this.options.shouldResubscribe; | ||
if (typeof shouldResubscribe === 'function') { | ||
shouldResubscribe = !!shouldResubscribe(this.options); | ||
} | ||
if (shouldResubscribe !== false && | ||
this.previousOptions && | ||
Object.keys(this.previousOptions).length > 0 && | ||
(!isEqual(this.previousOptions.variables, this.options.variables) || | ||
this.previousOptions.subscription !== this.options.subscription)) { | ||
this.endSubscription(); | ||
delete this.currentObservable.query; | ||
currentResult = this.getLoadingResult(); | ||
} | ||
this.initialize(this.options); | ||
this.startSubscription(); | ||
this.previousOptions = this.options; | ||
return tslib.__assign({}, currentResult, { variables: this.options.variables }); | ||
}; | ||
SubscriptionData.prototype.afterExecute = function () { | ||
this.isMounted = true; | ||
return this.unmount.bind(this); | ||
}; | ||
SubscriptionData.prototype.cleanup = function () { | ||
this.endSubscription(); | ||
delete this.currentObservable.query; | ||
}; | ||
SubscriptionData.prototype.initialize = function (options) { | ||
if (this.currentObservable.query) | ||
return; | ||
this.currentObservable.query = this.refreshClient().client.subscribe({ | ||
query: options.subscription, | ||
variables: options.variables, | ||
fetchPolicy: options.fetchPolicy | ||
}); | ||
}; | ||
SubscriptionData.prototype.startSubscription = function () { | ||
if (this.currentObservable.subscription) | ||
return; | ||
this.currentObservable.subscription = this.currentObservable.query.subscribe({ | ||
next: this.updateCurrentData.bind(this), | ||
error: this.updateError.bind(this), | ||
complete: this.completeSubscription.bind(this) | ||
}); | ||
}; | ||
SubscriptionData.prototype.getLoadingResult = function () { | ||
return { | ||
loading: true, | ||
error: undefined, | ||
data: undefined | ||
}; | ||
}; | ||
SubscriptionData.prototype.updateResult = function (result) { | ||
if (this.isMounted) { | ||
this.setResult(result); | ||
} | ||
}; | ||
SubscriptionData.prototype.updateCurrentData = function (result) { | ||
var onSubscriptionData = this.options.onSubscriptionData; | ||
if (onSubscriptionData) { | ||
onSubscriptionData({ | ||
client: this.refreshClient().client, | ||
subscriptionData: result | ||
}); | ||
} | ||
this.updateResult({ | ||
data: result.data, | ||
loading: false, | ||
error: undefined | ||
}); | ||
}; | ||
SubscriptionData.prototype.updateError = function (error) { | ||
this.updateResult({ | ||
error: error, | ||
loading: false | ||
}); | ||
}; | ||
SubscriptionData.prototype.completeSubscription = function () { | ||
var onSubscriptionComplete = this.options.onSubscriptionComplete; | ||
if (onSubscriptionComplete) | ||
onSubscriptionComplete(); | ||
this.endSubscription(); | ||
}; | ||
SubscriptionData.prototype.endSubscription = function () { | ||
if (this.currentObservable.subscription) { | ||
this.currentObservable.subscription.unsubscribe(); | ||
delete this.currentObservable.subscription; | ||
} | ||
}; | ||
return SubscriptionData; | ||
}(OperationData)); | ||
var queryData = getQueryDataRef(); | ||
queryData.setOptions(updatedOptions); | ||
queryData.context = context; | ||
(0, _react.useEffect)(function () { | ||
return queryData.afterExecute(); | ||
}); | ||
return queryData.execute(); | ||
} | ||
function useSubscription(subscription, options) { | ||
var context = React.useContext(reactCommon.getApolloContext()); | ||
var _a = React.useState({ | ||
loading: true, | ||
error: undefined, | ||
data: undefined | ||
}), result = _a[0], setResult = _a[1]; | ||
var updatedOptions = options | ||
? tslib.__assign({}, options, { subscription: subscription }) : { subscription: subscription }; | ||
var subscriptionDataRef = React.useRef(); | ||
function getSubscriptionDataRef() { | ||
if (!subscriptionDataRef.current) { | ||
subscriptionDataRef.current = new SubscriptionData({ | ||
options: updatedOptions, | ||
context: context, | ||
setResult: setResult | ||
}); | ||
} | ||
return subscriptionDataRef.current; | ||
} | ||
var subscriptionData = getSubscriptionDataRef(); | ||
subscriptionData.options = updatedOptions; | ||
subscriptionData.context = context; | ||
React.useEffect(function () { | ||
return subscriptionData.afterExecute(); | ||
var MutationData = function (_super) { | ||
(0, _tslib.__extends)(MutationData, _super); | ||
function MutationData(_a) { | ||
var options = _a.options, | ||
context = _a.context, | ||
result = _a.result, | ||
setResult = _a.setResult; | ||
var _this = _super.call(this, options, context) || this; | ||
_this.verifyDocumentType(options.mutation, _reactCommon.DocumentType.Mutation); | ||
_this.result = result; | ||
_this.setResult = setResult; | ||
_this.mostRecentMutationId = 0; | ||
return _this; | ||
} | ||
MutationData.prototype.execute = function (result) { | ||
var _this = this; | ||
this.verifyDocumentType(this.getOptions().mutation, _reactCommon.DocumentType.Mutation); | ||
var runMutation = function (options) { | ||
return _this.runMutation(options); | ||
}; | ||
return [runMutation, result]; | ||
}; | ||
MutationData.prototype.afterExecute = function () { | ||
this.isMounted = true; | ||
return this.unmount.bind(this); | ||
}; | ||
MutationData.prototype.cleanup = function () {}; | ||
MutationData.prototype.runMutation = function (mutationFunctionOptions) { | ||
var _this = this; | ||
if (mutationFunctionOptions === void 0) { | ||
mutationFunctionOptions = {}; | ||
} | ||
this.onMutationStart(); | ||
var mutationId = this.generateNewMutationId(); | ||
return this.mutate(mutationFunctionOptions).then(function (response) { | ||
_this.onMutationCompleted(response, mutationId); | ||
return response; | ||
}).catch(function (error) { | ||
_this.onMutationError(error, mutationId); | ||
if (!_this.getOptions().onError) throw error; | ||
}); | ||
}; | ||
MutationData.prototype.mutate = function (mutationFunctionOptions) { | ||
var _a = this.getOptions(), | ||
mutation = _a.mutation, | ||
variables = _a.variables, | ||
optimisticResponse = _a.optimisticResponse, | ||
update = _a.update, | ||
_b = _a.context, | ||
mutationContext = _b === void 0 ? {} : _b, | ||
_c = _a.awaitRefetchQueries, | ||
awaitRefetchQueries = _c === void 0 ? false : _c, | ||
fetchPolicy = _a.fetchPolicy; | ||
var mutateOptions = (0, _tslib.__assign)({}, mutationFunctionOptions); | ||
var mutateVariables = Object.assign({}, variables, mutateOptions.variables); | ||
delete mutateOptions.variables; | ||
return this.refreshClient().client.mutate((0, _tslib.__assign)({ | ||
mutation: mutation, | ||
optimisticResponse: optimisticResponse, | ||
refetchQueries: mutateOptions.refetchQueries || this.getOptions().refetchQueries, | ||
awaitRefetchQueries: awaitRefetchQueries, | ||
update: update, | ||
context: mutationContext, | ||
fetchPolicy: fetchPolicy, | ||
variables: mutateVariables | ||
}, mutateOptions)); | ||
}; | ||
MutationData.prototype.onMutationStart = function () { | ||
if (!this.result.loading && !this.getOptions().ignoreResults) { | ||
this.updateResult({ | ||
loading: true, | ||
error: undefined, | ||
data: undefined, | ||
called: true | ||
}); | ||
return subscriptionData.execute(result); | ||
} | ||
}; | ||
MutationData.prototype.onMutationCompleted = function (response, mutationId) { | ||
var _a = this.getOptions(), | ||
onCompleted = _a.onCompleted, | ||
ignoreResults = _a.ignoreResults; | ||
var data = response.data, | ||
errors = response.errors; | ||
var error = errors && errors.length > 0 ? new _apolloClient.ApolloError({ | ||
graphQLErrors: errors | ||
}) : undefined; | ||
var callOncomplete = function () { | ||
return onCompleted ? onCompleted(data) : null; | ||
}; | ||
if (this.isMostRecentMutation(mutationId) && !ignoreResults) { | ||
this.updateResult({ | ||
called: true, | ||
loading: false, | ||
data: data, | ||
error: error | ||
}); | ||
} | ||
callOncomplete(); | ||
}; | ||
MutationData.prototype.onMutationError = function (error, mutationId) { | ||
var onError = this.getOptions().onError; | ||
if (this.isMostRecentMutation(mutationId)) { | ||
this.updateResult({ | ||
loading: false, | ||
error: error, | ||
data: undefined, | ||
called: true | ||
}); | ||
} | ||
if (onError) { | ||
onError(error); | ||
} | ||
}; | ||
MutationData.prototype.generateNewMutationId = function () { | ||
return ++this.mostRecentMutationId; | ||
}; | ||
MutationData.prototype.isMostRecentMutation = function (mutationId) { | ||
return this.mostRecentMutationId === mutationId; | ||
}; | ||
MutationData.prototype.updateResult = function (result) { | ||
if (this.isMounted && (!this.previousResult || !(0, _apolloUtilities.isEqual)(this.previousResult, result))) { | ||
this.setResult(result); | ||
this.previousResult = result; | ||
} | ||
}; | ||
return MutationData; | ||
}(OperationData); | ||
function useMutation(mutation, options) { | ||
var context = (0, _react.useContext)((0, _reactCommon.getApolloContext)()); | ||
var _a = (0, _react.useState)({ | ||
called: false, | ||
loading: false | ||
}), | ||
result = _a[0], | ||
setResult = _a[1]; | ||
var updatedOptions = options ? (0, _tslib.__assign)({}, options, { | ||
mutation: mutation | ||
}) : { | ||
mutation: mutation | ||
}; | ||
var mutationDataRef = (0, _react.useRef)(); | ||
function getMutationDataRef() { | ||
if (!mutationDataRef.current) { | ||
mutationDataRef.current = new MutationData({ | ||
options: updatedOptions, | ||
context: context, | ||
result: result, | ||
setResult: setResult | ||
}); | ||
} | ||
return mutationDataRef.current; | ||
} | ||
function useApolloClient() { | ||
var client = React__default.useContext(reactCommon.getApolloContext()).client; | ||
process.env.NODE_ENV === "production" ? tsInvariant.invariant(client) : tsInvariant.invariant(client, 'No Apollo Client instance can be found. Please ensure that you ' + | ||
'have called `ApolloProvider` higher up in your tree.'); | ||
return client; | ||
var mutationData = getMutationDataRef(); | ||
mutationData.setOptions(updatedOptions); | ||
mutationData.context = context; | ||
(0, _react.useEffect)(function () { | ||
return mutationData.afterExecute(); | ||
}); | ||
return mutationData.execute(result); | ||
} | ||
var SubscriptionData = function (_super) { | ||
(0, _tslib.__extends)(SubscriptionData, _super); | ||
function SubscriptionData(_a) { | ||
var options = _a.options, | ||
context = _a.context, | ||
setResult = _a.setResult; | ||
var _this = _super.call(this, options, context) || this; | ||
_this.currentObservable = {}; | ||
_this.setResult = setResult; | ||
_this.initialize(options); | ||
return _this; | ||
} | ||
function makeDefaultQueryInfo() { | ||
return { | ||
seen: false, | ||
observable: null | ||
}; | ||
} | ||
var RenderPromises = (function () { | ||
function RenderPromises() { | ||
this.queryPromises = new Map(); | ||
this.queryInfoTrie = new Map(); | ||
} | ||
RenderPromises.prototype.registerSSRObservable = function (observable, props) { | ||
this.lookupQueryInfo(props).observable = observable; | ||
}; | ||
RenderPromises.prototype.getSSRObservable = function (props) { | ||
return this.lookupQueryInfo(props).observable; | ||
}; | ||
RenderPromises.prototype.addQueryPromise = function (queryInstance, finish) { | ||
var info = this.lookupQueryInfo(queryInstance.options); | ||
if (!info.seen) { | ||
this.queryPromises.set(queryInstance.options, new Promise(function (resolve) { | ||
resolve(queryInstance.fetchData()); | ||
})); | ||
return null; | ||
} | ||
return finish(); | ||
}; | ||
RenderPromises.prototype.hasPromises = function () { | ||
return this.queryPromises.size > 0; | ||
}; | ||
RenderPromises.prototype.consumeAndAwaitPromises = function () { | ||
var _this = this; | ||
var promises = []; | ||
this.queryPromises.forEach(function (promise, queryInstance) { | ||
_this.lookupQueryInfo(queryInstance).seen = true; | ||
promises.push(promise); | ||
}); | ||
this.queryPromises.clear(); | ||
return Promise.all(promises); | ||
}; | ||
RenderPromises.prototype.lookupQueryInfo = function (props) { | ||
var queryInfoTrie = this.queryInfoTrie; | ||
var query = props.query, variables = props.variables; | ||
var varMap = queryInfoTrie.get(query) || new Map(); | ||
if (!queryInfoTrie.has(query)) | ||
queryInfoTrie.set(query, varMap); | ||
var variablesString = JSON.stringify(variables); | ||
var info = varMap.get(variablesString) || makeDefaultQueryInfo(); | ||
if (!varMap.has(variablesString)) | ||
varMap.set(variablesString, info); | ||
return info; | ||
}; | ||
return RenderPromises; | ||
}()); | ||
function getDataFromTree(tree, context) { | ||
if (context === void 0) { context = {}; } | ||
return getMarkupFromTree({ | ||
tree: tree, | ||
context: context, | ||
renderFunction: require('react-dom/server').renderToStaticMarkup | ||
SubscriptionData.prototype.execute = function (result) { | ||
var currentResult = result; | ||
if (this.refreshClient().isNew) { | ||
currentResult = this.getLoadingResult(); | ||
} | ||
var shouldResubscribe = this.getOptions().shouldResubscribe; | ||
if (typeof shouldResubscribe === 'function') { | ||
shouldResubscribe = !!shouldResubscribe(this.getOptions()); | ||
} | ||
if (shouldResubscribe !== false && this.previousOptions && Object.keys(this.previousOptions).length > 0 && (this.previousOptions.subscription !== this.getOptions().subscription || !(0, _apolloUtilities.isEqual)(this.previousOptions.variables, this.getOptions().variables))) { | ||
this.endSubscription(); | ||
delete this.currentObservable.query; | ||
currentResult = this.getLoadingResult(); | ||
} | ||
this.initialize(this.getOptions()); | ||
this.startSubscription(); | ||
this.previousOptions = this.getOptions(); | ||
return (0, _tslib.__assign)({}, currentResult, { | ||
variables: this.getOptions().variables | ||
}); | ||
}; | ||
SubscriptionData.prototype.afterExecute = function () { | ||
this.isMounted = true; | ||
return this.unmount.bind(this); | ||
}; | ||
SubscriptionData.prototype.cleanup = function () { | ||
this.endSubscription(); | ||
delete this.currentObservable.query; | ||
}; | ||
SubscriptionData.prototype.initialize = function (options) { | ||
if (this.currentObservable.query) return; | ||
this.currentObservable.query = this.refreshClient().client.subscribe({ | ||
query: options.subscription, | ||
variables: options.variables, | ||
fetchPolicy: options.fetchPolicy | ||
}); | ||
}; | ||
SubscriptionData.prototype.startSubscription = function () { | ||
if (this.currentObservable.subscription) return; | ||
this.currentObservable.subscription = this.currentObservable.query.subscribe({ | ||
next: this.updateCurrentData.bind(this), | ||
error: this.updateError.bind(this), | ||
complete: this.completeSubscription.bind(this) | ||
}); | ||
}; | ||
SubscriptionData.prototype.getLoadingResult = function () { | ||
return { | ||
loading: true, | ||
error: undefined, | ||
data: undefined | ||
}; | ||
}; | ||
SubscriptionData.prototype.updateResult = function (result) { | ||
if (this.isMounted) { | ||
this.setResult(result); | ||
} | ||
}; | ||
SubscriptionData.prototype.updateCurrentData = function (result) { | ||
var onSubscriptionData = this.getOptions().onSubscriptionData; | ||
if (onSubscriptionData) { | ||
onSubscriptionData({ | ||
client: this.refreshClient().client, | ||
subscriptionData: result | ||
}); | ||
} | ||
this.updateResult({ | ||
data: result.data, | ||
loading: false, | ||
error: undefined | ||
}); | ||
}; | ||
SubscriptionData.prototype.updateError = function (error) { | ||
this.updateResult({ | ||
error: error, | ||
loading: false | ||
}); | ||
}; | ||
SubscriptionData.prototype.completeSubscription = function () { | ||
var onSubscriptionComplete = this.getOptions().onSubscriptionComplete; | ||
if (onSubscriptionComplete) onSubscriptionComplete(); | ||
this.endSubscription(); | ||
}; | ||
SubscriptionData.prototype.endSubscription = function () { | ||
if (this.currentObservable.subscription) { | ||
this.currentObservable.subscription.unsubscribe(); | ||
delete this.currentObservable.subscription; | ||
} | ||
}; | ||
return SubscriptionData; | ||
}(OperationData); | ||
function useSubscription(subscription, options) { | ||
var context = (0, _react.useContext)((0, _reactCommon.getApolloContext)()); | ||
var _a = (0, _react.useState)({ | ||
loading: true, | ||
error: undefined, | ||
data: undefined | ||
}), | ||
result = _a[0], | ||
setResult = _a[1]; | ||
var updatedOptions = options ? (0, _tslib.__assign)({}, options, { | ||
subscription: subscription | ||
}) : { | ||
subscription: subscription | ||
}; | ||
var subscriptionDataRef = (0, _react.useRef)(); | ||
function getSubscriptionDataRef() { | ||
if (!subscriptionDataRef.current) { | ||
subscriptionDataRef.current = new SubscriptionData({ | ||
options: updatedOptions, | ||
context: context, | ||
setResult: setResult | ||
}); | ||
} | ||
return subscriptionDataRef.current; | ||
} | ||
function getMarkupFromTree(_a) { | ||
var tree = _a.tree, _b = _a.context, context = _b === void 0 ? {} : _b, _c = _a.renderFunction, renderFunction = _c === void 0 ? require('react-dom/server').renderToStaticMarkup : _c; | ||
var renderPromises = new RenderPromises(); | ||
function process() { | ||
var ApolloContext = reactCommon.getApolloContext(); | ||
var html = renderFunction(React__default.createElement(ApolloContext.Provider, { value: tslib.__assign({}, context, { renderPromises: renderPromises }) }, tree)); | ||
return renderPromises.hasPromises() | ||
? renderPromises.consumeAndAwaitPromises().then(process) | ||
: html; | ||
} | ||
return Promise.resolve().then(process); | ||
var subscriptionData = getSubscriptionDataRef(); | ||
subscriptionData.setOptions(updatedOptions); | ||
subscriptionData.context = context; | ||
(0, _react.useEffect)(function () { | ||
return subscriptionData.afterExecute(); | ||
}); | ||
return subscriptionData.execute(result); | ||
} | ||
function useApolloClient() { | ||
var client = _react.default.useContext((0, _reactCommon.getApolloContext)()).client; | ||
process.env.NODE_ENV === "production" ? (0, _tsInvariant.invariant)(client, 1) : (0, _tsInvariant.invariant)(client, 'No Apollo Client instance can be found. Please ensure that you ' + 'have called `ApolloProvider` higher up in your tree.'); | ||
return client; | ||
} | ||
function makeDefaultQueryInfo() { | ||
return { | ||
seen: false, | ||
observable: null | ||
}; | ||
} | ||
var RenderPromises = function () { | ||
function RenderPromises() { | ||
this.queryPromises = new Map(); | ||
this.queryInfoTrie = new Map(); | ||
} | ||
function renderToStringWithData(component) { | ||
return getMarkupFromTree({ | ||
tree: component, | ||
renderFunction: require('react-dom/server').renderToString | ||
}); | ||
RenderPromises.prototype.registerSSRObservable = function (observable, props) { | ||
this.lookupQueryInfo(props).observable = observable; | ||
}; | ||
RenderPromises.prototype.getSSRObservable = function (props) { | ||
return this.lookupQueryInfo(props).observable; | ||
}; | ||
RenderPromises.prototype.addQueryPromise = function (queryInstance, finish) { | ||
var info = this.lookupQueryInfo(queryInstance.getOptions()); | ||
if (!info.seen) { | ||
this.queryPromises.set(queryInstance.getOptions(), new Promise(function (resolve) { | ||
resolve(queryInstance.fetchData()); | ||
})); | ||
return null; | ||
} | ||
return finish(); | ||
}; | ||
RenderPromises.prototype.hasPromises = function () { | ||
return this.queryPromises.size > 0; | ||
}; | ||
RenderPromises.prototype.consumeAndAwaitPromises = function () { | ||
var _this = this; | ||
var promises = []; | ||
this.queryPromises.forEach(function (promise, queryInstance) { | ||
_this.lookupQueryInfo(queryInstance).seen = true; | ||
promises.push(promise); | ||
}); | ||
this.queryPromises.clear(); | ||
return Promise.all(promises); | ||
}; | ||
RenderPromises.prototype.lookupQueryInfo = function (props) { | ||
var queryInfoTrie = this.queryInfoTrie; | ||
var query = props.query, | ||
variables = props.variables; | ||
var varMap = queryInfoTrie.get(query) || new Map(); | ||
if (!queryInfoTrie.has(query)) queryInfoTrie.set(query, varMap); | ||
var variablesString = JSON.stringify(variables); | ||
var info = varMap.get(variablesString) || makeDefaultQueryInfo(); | ||
if (!varMap.has(variablesString)) varMap.set(variablesString, info); | ||
return info; | ||
}; | ||
return RenderPromises; | ||
}(); | ||
function getDataFromTree(tree, context) { | ||
if (context === void 0) { | ||
context = {}; | ||
} | ||
Object.defineProperty(exports, 'ApolloConsumer', { | ||
enumerable: true, | ||
get: function () { | ||
return reactCommon.ApolloConsumer; | ||
} | ||
return getMarkupFromTree({ | ||
tree: tree, | ||
context: context, | ||
renderFunction: require('react-dom/server').renderToStaticMarkup | ||
}); | ||
Object.defineProperty(exports, 'ApolloProvider', { | ||
enumerable: true, | ||
get: function () { | ||
return reactCommon.ApolloProvider; | ||
} | ||
} | ||
function getMarkupFromTree(_a) { | ||
var tree = _a.tree, | ||
_b = _a.context, | ||
context = _b === void 0 ? {} : _b, | ||
_c = _a.renderFunction, | ||
renderFunction = _c === void 0 ? require('react-dom/server').renderToStaticMarkup : _c; | ||
var renderPromises = new RenderPromises(); | ||
function process() { | ||
var ApolloContext = (0, _reactCommon.getApolloContext)(); | ||
var html = renderFunction(_react.default.createElement(ApolloContext.Provider, { | ||
value: (0, _tslib.__assign)({}, context, { | ||
renderPromises: renderPromises | ||
}) | ||
}, tree)); | ||
return renderPromises.hasPromises() ? renderPromises.consumeAndAwaitPromises().then(process) : html; | ||
} | ||
return Promise.resolve().then(process); | ||
} | ||
function renderToStringWithData(component) { | ||
return getMarkupFromTree({ | ||
tree: component, | ||
renderFunction: require('react-dom/server').renderToString | ||
}); | ||
Object.defineProperty(exports, 'getApolloContext', { | ||
enumerable: true, | ||
get: function () { | ||
return reactCommon.getApolloContext; | ||
} | ||
}); | ||
Object.defineProperty(exports, 'resetApolloContext', { | ||
enumerable: true, | ||
get: function () { | ||
return reactCommon.resetApolloContext; | ||
} | ||
}); | ||
exports.getDataFromTree = getDataFromTree; | ||
exports.getMarkupFromTree = getMarkupFromTree; | ||
exports.renderToStringWithData = renderToStringWithData; | ||
exports.useApolloClient = useApolloClient; | ||
exports.useMutation = useMutation; | ||
exports.useQuery = useQuery; | ||
exports.useSubscription = useSubscription; | ||
} | ||
Object.defineProperty(exports, '__esModule', { value: true }); | ||
})); | ||
}); |
@@ -22,5 +22,5 @@ import * as tslib_1 from "tslib"; | ||
RenderPromises.prototype.addQueryPromise = function (queryInstance, finish) { | ||
var info = this.lookupQueryInfo(queryInstance.options); | ||
var info = this.lookupQueryInfo(queryInstance.getOptions()); | ||
if (!info.seen) { | ||
this.queryPromises.set(queryInstance.options, new Promise(function (resolve) { | ||
this.queryPromises.set(queryInstance.getOptions(), new Promise(function (resolve) { | ||
resolve(queryInstance.fetchData()); | ||
@@ -27,0 +27,0 @@ })); |
@@ -22,9 +22,7 @@ import * as tslib_1 from "tslib"; | ||
var mutationData = getMutationDataRef(); | ||
mutationData.options = updatedOptions; | ||
mutationData.setOptions(updatedOptions); | ||
mutationData.context = context; | ||
useEffect(function () { | ||
return mutationData.afterExecute(); | ||
}); | ||
useEffect(function () { return mutationData.afterExecute(); }); | ||
return mutationData.execute(result); | ||
} | ||
//# sourceMappingURL=useMutation.js.map |
@@ -21,9 +21,7 @@ import * as tslib_1 from "tslib"; | ||
var queryData = getQueryDataRef(); | ||
queryData.options = updatedOptions; | ||
queryData.setOptions(updatedOptions); | ||
queryData.context = context; | ||
useEffect(function () { | ||
return queryData.afterExecute(); | ||
}); | ||
useEffect(function () { return queryData.afterExecute(); }); | ||
return queryData.execute(); | ||
} | ||
//# sourceMappingURL=useQuery.js.map |
@@ -26,9 +26,7 @@ import * as tslib_1 from "tslib"; | ||
var subscriptionData = getSubscriptionDataRef(); | ||
subscriptionData.options = updatedOptions; | ||
subscriptionData.setOptions(updatedOptions); | ||
subscriptionData.context = context; | ||
useEffect(function () { | ||
return subscriptionData.afterExecute(); | ||
}); | ||
useEffect(function () { return subscriptionData.afterExecute(); }); | ||
return subscriptionData.execute(result); | ||
} | ||
//# sourceMappingURL=useSubscription.js.map |
{ | ||
"name": "@apollo/react-hooks", | ||
"description": "React Apollo Hooks.", | ||
"version": "0.1.0-beta.7", | ||
"version": "0.1.0-beta.8", | ||
"author": "opensource@apollographql.com", | ||
@@ -15,2 +15,5 @@ "keywords": [ | ||
"module": "./lib/react-hooks.esm.js", | ||
"react-native": { | ||
"react-dom/server": false | ||
}, | ||
"typings": "./lib/index.d.ts", | ||
@@ -23,10 +26,14 @@ "repository": { | ||
"scripts": { | ||
"clean": "rm -Rf ./node_modules ./lib/* ./meta/bundlesize/* ./meta/coverage/*", | ||
"clean": "rm -Rf ./lib/* ./meta/bundlesize/* ./meta/coverage/*", | ||
"prepare": "npm run build", | ||
"prebuild": "npm run clean", | ||
"build": "npx -p typescript tsc -p ./config", | ||
"build": "npx tsc -p ./config", | ||
"postbuild": "npx rollup -c ./config/rollup.config.js", | ||
"watch": "node ../../node_modules/tsc-watch/lib/tsc-watch.js --onSuccess \"npm run postbuild\" -p ./config", | ||
"watch": "npx tsc-watch --onSuccess \"npm run postbuild\" -p ./config", | ||
"predeploy": "npm run build", | ||
"deploy": "npm publish --tag beta" | ||
"deploy": "npm publish --tag beta", | ||
"test": "npx jest --config ../../config/jest.config.js --testPathPattern packages/hooks", | ||
"test:watch": "npx jest --config ../../config/jest.config.js --testPathPattern packages/hooks --watch", | ||
"test:cjs": "npm run build && npx jest --config ../../config/jest.cjs.config.js --testPathPattern packages/hooks", | ||
"test:umd": "npm run build && npx jest --config ../../config/jest.umd.config.js --testPathPattern packages/hooks" | ||
}, | ||
@@ -36,6 +43,7 @@ "peerDependencies": { | ||
"graphql": "^14.2.1", | ||
"react": "^16.8.6" | ||
"react": "^16.8.0" | ||
}, | ||
"dependencies": { | ||
"@apollo/react-common": "^0.1.0-beta.5", | ||
"@apollo/react-common": "^0.1.0-beta.6", | ||
"apollo-utilities": "^1.3.2", | ||
"ts-invariant": "^0.4.2", | ||
@@ -50,3 +58,9 @@ "tslib": "^1.9.3" | ||
}, | ||
"gitHead": "dbdffdd7edc415f4813df0e6034ac68fe1d8cfa4" | ||
"devDependencies": { | ||
"jest": "^24.8.0", | ||
"rollup": "^1.15.5", | ||
"tsc-watch": "^2.2.1", | ||
"typescript": "^3.5.2" | ||
}, | ||
"gitHead": "f0ad14e4304a9b58381b292fe8ad739a0ab4534b" | ||
} |
342
README.md
@@ -1,3 +0,341 @@ | ||
# React Apollo - Hooks | ||
# <a href="https://www.apollographql.com/"><img src="https://user-images.githubusercontent.com/841294/53402609-b97a2180-39ba-11e9-8100-812bab86357c.png" height="100" alt="React Apollo"></a> | ||
React Apollo Hooks. | ||
## React Apollo - Hooks | ||
[![npm version](https://badge.fury.io/js/%40apollo%2Freact-hooks.svg)](https://badge.fury.io/js/%40apollo%2Freact-hooks) | ||
[![Build Status](https://circleci.com/gh/apollographql/react-apollo.svg?style=svg)](https://circleci.com/gh/apollographql/react-apollo) | ||
[![Join the community on Spectrum](https://withspectrum.github.io/badge/badge.svg)](https://spectrum.chat/apollo) | ||
React Apollo [Hooks](https://reactjs.org/docs/hooks-intro.html). | ||
> **NOTE:** Full React Apollo Hooks usage documentation is coming soon, and when ready will be made available in the main [React Apollo documentation](https://www.apollographql.com/docs/react/). The contents of this README are intended to help beta testers, and will change. | ||
### Contents | ||
1. [Installation](#installation) | ||
2. [Hooks Overview](#hooks-overview) | ||
- [`useQuery`](#useQuery) | ||
- [`useMutation`](#useMutation) | ||
- [`useSubscription`](#useSubscription) | ||
- [`useApolloClient`](#useApolloClient) | ||
3. [Reference]() | ||
### Installation | ||
``` | ||
npm install @apollo/react-hooks | ||
``` | ||
### Hooks Overview | ||
<a name="useQuery"></a> | ||
#### a) [`useQuery`](https://github.com/apollographql/react-apollo/blob/release-3.0.0/packages/hooks/src/useQuery.ts) | ||
**Function:** | ||
```ts | ||
export function useQuery<TData = any, TVariables = OperationVariables>( | ||
query: DocumentNode, | ||
options?: QueryHookOptions<TData, TVariables> | ||
): QueryResult<TData, TVariables> | ||
``` | ||
**Options:** | ||
```ts | ||
query?: DocumentNode; | ||
displayName?: string; | ||
skip?: boolean; | ||
onCompleted?: (data: TData) => void; | ||
onError?: (error: ApolloError) => void; | ||
ssr?: boolean; | ||
variables?: TVariables; | ||
fetchPolicy?: WatchQueryFetchPolicy; | ||
errorPolicy?: ErrorPolicy; | ||
pollInterval?: number; | ||
client?: ApolloClient<any>; | ||
notifyOnNetworkStatusChange?: boolean; | ||
context?: Context; | ||
partialRefetch?: boolean; | ||
returnPartialData?: boolean | ||
``` | ||
**Result:** | ||
- client: ApolloClient<any>; | ||
- data: TData | undefined; | ||
- error?: ApolloError; | ||
- loading: boolean; | ||
- networkStatus: NetworkStatus; | ||
- fetchMore: any; | ||
**Example (from the [Hooks demo app](https://github.com/apollographql/react-apollo/tree/release-3.0.0/examples/hooks)):** | ||
```jsx | ||
const GET_ROCKET_INVENTORY = gql` | ||
query getRocketInventory { | ||
rocketInventory { | ||
id | ||
model | ||
year | ||
stock | ||
} | ||
} | ||
`; | ||
export function RocketInventoryList() { | ||
const { loading, data } = useQuery(GET_ROCKET_INVENTORY); | ||
return ( | ||
<Row className="rocket-inventory-list mt-4"> | ||
<Col sm="12"> | ||
<h3>Available Inventory</h3> | ||
{loading ? ( | ||
<p>Loading ...</p> | ||
) : ( | ||
<table className="table table-striped table-bordered"> | ||
<thead> | ||
<tr> | ||
<th>Model</th> | ||
<th>Year</th> | ||
<th>Stock</th> | ||
</tr> | ||
</thead> | ||
<tbody> | ||
{data.rocketInventory.map((inventory: RocketInventory) => ( | ||
<tr | ||
key={`${inventory.model}-${inventory.year}-${ | ||
inventory.stock | ||
}`} | ||
> | ||
<td>{inventory.model}</td> | ||
<td>{inventory.year}</td> | ||
<td>{inventory.stock}</td> | ||
</tr> | ||
))} | ||
</tbody> | ||
</table> | ||
)} | ||
</Col> | ||
</Row> | ||
); | ||
} | ||
``` | ||
<a name="useMutation"></a> | ||
#### b) [`useMutation`](https://github.com/apollographql/react-apollo/blob/release-3.0.0/packages/hooks/src/useMutation.ts) | ||
**Function:** | ||
```ts | ||
export function useMutation<TData = any, TVariables = OperationVariables>( | ||
mutation: DocumentNode, | ||
options?: MutationHookOptions<TData, TVariables> | ||
): MutationTuple<TData, TVariables> | ||
``` | ||
**Options:** | ||
```ts | ||
mutation?: DocumentNode; | ||
variables?: TVariables; | ||
optimisticResponse?: TData; | ||
refetchQueries?: Array<string | PureQueryOptions> | RefetchQueriesFunction; | ||
awaitRefetchQueries?: boolean; | ||
errorPolicy?: ErrorPolicy; | ||
update?: MutationUpdaterFn<TData>; | ||
client?: ApolloClient<object>; | ||
notifyOnNetworkStatusChange?: boolean; | ||
context?: Context; | ||
onCompleted?: (data: TData) => void; | ||
onError?: (error: ApolloError) => void; | ||
fetchPolicy?: WatchQueryFetchPolicy; | ||
ignoreResults?: boolean; | ||
``` | ||
**Result:** | ||
```ts | ||
[ | ||
( | ||
options?: MutationFunctionOptions<TData, TVariables> | ||
) => Promise<void | ExecutionResult<TData>>, | ||
{ | ||
data?: TData; | ||
error?: ApolloError; | ||
loading: boolean; | ||
called: boolean; | ||
client?: ApolloClient<object> | ||
} | ||
]; | ||
``` | ||
**Example (from the [Hooks demo app](https://github.com/apollographql/react-apollo/tree/release-3.0.0/examples/hooks)):** | ||
```jsx | ||
const SAVE_ROCKET = gql` | ||
mutation saveRocket($rocket: RocketInput!) { | ||
saveRocket(rocket: $rocket) { | ||
model | ||
} | ||
} | ||
`; | ||
export function NewRocketForm() { | ||
const [model, setModel] = useState(''); | ||
const [year, setYear] = useState(0); | ||
const [stock, setStock] = useState(0); | ||
const [saveRocket, { error, data }] = useMutation< | ||
{ | ||
saveRocket: RocketInventory; | ||
}, | ||
{ rocket: NewRocketDetails } | ||
>(SAVE_ROCKET, { | ||
variables: { rocket: { model: model, year: +year, stock: +stock } }, | ||
refetchQueries: ['getRocketInventory'] | ||
}); | ||
return ( | ||
<div className="new-rocket-form mt-3"> | ||
<h3>Add a Rocket</h3> | ||
{error ? <Alert color="danger">Oh no! {error.message}</Alert> : null} | ||
{data && data.saveRocket ? ( | ||
<Alert color="success"> | ||
Model <strong>{data.saveRocket.model}</strong> added! | ||
</Alert> | ||
) : null} | ||
<Form style={{ border: '1px solid #ddd', padding: '15px' }}> | ||
<Row> | ||
<Col sm="6"> | ||
<FormGroup> | ||
<Label for="model">Model</Label> | ||
<Input | ||
type="text" | ||
name="model" | ||
id="model" | ||
onChange={e => setModel(e.target.value)} | ||
/> | ||
</FormGroup> | ||
</Col> | ||
<Col sm="3"> | ||
<FormGroup> | ||
<Label for="year">Year</Label> | ||
<Input | ||
type="number" | ||
name="year" | ||
id="year" | ||
onChange={e => setYear(+e.target.value)} | ||
/> | ||
</FormGroup> | ||
</Col> | ||
<Col sm="3"> | ||
<FormGroup> | ||
<Label for="stock">Stock</Label> | ||
<Input | ||
type="number" | ||
name="stock" | ||
id="stock" | ||
onChange={e => setStock(+e.target.value)} | ||
/> | ||
</FormGroup> | ||
</Col> | ||
</Row> | ||
<Row> | ||
<Col | ||
sm="12" | ||
className="text-right" | ||
onClick={e => { | ||
e.preventDefault(); | ||
if (model && year && stock) { | ||
saveRocket(); | ||
} | ||
}} | ||
> | ||
<Button>Add</Button> | ||
</Col> | ||
</Row> | ||
</Form> | ||
</div> | ||
); | ||
} | ||
``` | ||
<a name="useSubscription"></a> | ||
#### c) [`useSubscription`](https://github.com/apollographql/react-apollo/blob/release-3.0.0/packages/hooks/src/useSubscription.ts) | ||
**Function:** | ||
```ts | ||
export function useSubscription<TData = any, TVariables = OperationVariables>( | ||
subscription: DocumentNode, | ||
options?: SubscriptionHookOptions<TData, TVariables> | ||
) | ||
``` | ||
**Options:** | ||
```ts | ||
subscription?: DocumentNode; | ||
variables?: TVariables; | ||
fetchPolicy?: FetchPolicy; | ||
shouldResubscribe?: boolean | ((options: BaseSubscriptionOptions<TData, TVariables>) => boolean); | ||
client?: ApolloClient<object>; | ||
onSubscriptionData?: (options: OnSubscriptionDataOptions<TData>) => any; | ||
onSubscriptionComplete?: () => void; | ||
``` | ||
**Example (from the [Hooks demo app](https://github.com/apollographql/react-apollo/tree/release-3.0.0/examples/hooks)):** | ||
```jsx | ||
const LATEST_NEWS = gql` | ||
subscription getLatestNews { | ||
latestNews { | ||
content | ||
} | ||
} | ||
`; | ||
export function LatestNews() { | ||
const { loading, data } = useSubscription<News>(LATEST_NEWS); | ||
return ( | ||
<Card className="bg-light"> | ||
<CardBody> | ||
<CardTitle> | ||
<h5>Latest News</h5> | ||
</CardTitle> | ||
<CardText>{loading ? 'Loading...' : data!.latestNews.content}</CardText> | ||
</CardBody> | ||
</Card> | ||
); | ||
} | ||
``` | ||
<a name="useApolloClient"></a> | ||
#### d) [`useApolloClient`](https://github.com/apollographql/react-apollo/blob/release-3.0.0/packages/hooks/src/useApolloClient.ts) | ||
**Function:** | ||
```ts | ||
export function useApolloClient(): ApolloClient<object> | ||
``` | ||
**Result:** | ||
`ApolloClient` instance stored in the current Context. | ||
**Example:** | ||
```jsx | ||
const client = useApolloClient(); | ||
consol.log('AC instance stored in the Context', client); | ||
``` | ||
### Reference | ||
- Main [Apollo Client / React Apollo documentation](https://www.apollographql.com/docs/react/) | ||
- `useQuery`, `useMutation` and `useSubscription` [Hooks demo app](https://github.com/apollographql/react-apollo/tree/release-3.0.0/examples/hooks) | ||
- Need help? Join us in the [Apollo Spectrum community](https://spectrum.chat/apollo) | ||
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
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
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
339676
46
342
7
4
3045
3