react-apollo
Version:
React data container for Apollo Client
1,031 lines (1,020 loc) • 54.7 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('prop-types'), require('apollo-client'), require('react-dom/server')) :
typeof define === 'function' && define.amd ? define(['exports', 'react', 'prop-types', 'apollo-client', 'react-dom/server'], factory) :
(factory((global['react-apollo'] = {}),global.React,global.PropTypes,global.apolloClient,global.ReactDOM));
}(this, (function (exports,React,PropTypes,apolloClient,ReactDOM) { 'use strict';
function getProps(element) {
return element.props || element.attributes;
}
function isReactElement(element) {
return !!element.type;
}
function isComponentClass(Comp) {
return Comp.prototype && (Comp.prototype.render || Comp.prototype.isReactComponent);
}
function providesChildContext(instance) {
return !!instance.getChildContext;
}
function walkTree(element, context, visitor) {
if (Array.isArray(element)) {
element.forEach(function (item) { return walkTree(item, context, visitor); });
return;
}
if (!element) {
return;
}
if (isReactElement(element)) {
if (typeof element.type === 'function') {
var Comp = element.type;
var props = Object.assign({}, Comp.defaultProps, getProps(element));
var childContext_1 = context;
var child = void 0;
if (isComponentClass(Comp)) {
var instance_1 = new Comp(props, context);
instance_1.props = instance_1.props || props;
instance_1.context = instance_1.context || context;
instance_1.state = instance_1.state || null;
instance_1.setState = function (newState) {
if (typeof newState === 'function') {
newState = newState(instance_1.state, instance_1.props, instance_1.context);
}
instance_1.state = Object.assign({}, instance_1.state, newState);
};
if (instance_1.componentWillMount) {
instance_1.componentWillMount();
}
if (providesChildContext(instance_1)) {
childContext_1 = Object.assign({}, context, instance_1.getChildContext());
}
if (visitor(element, instance_1, context, childContext_1) === false) {
return;
}
child = instance_1.render();
}
else {
if (visitor(element, null, context) === false) {
return;
}
child = Comp(props, context);
}
if (child) {
if (Array.isArray(child)) {
child.forEach(function (item) { return walkTree(item, childContext_1, visitor); });
}
else {
walkTree(child, childContext_1, visitor);
}
}
}
else {
if (visitor(element, null, context) === false) {
return;
}
if (element.props && element.props.children) {
React.Children.forEach(element.props.children, function (child) {
if (child) {
walkTree(child, context, visitor);
}
});
}
}
}
else if (typeof element === 'string' || typeof element === 'number') {
visitor(element, null, context);
}
}
function hasFetchDataFunction(instance) {
return typeof instance.fetchData === 'function';
}
function isPromise(promise) {
return typeof promise.then === 'function';
}
function getPromisesFromTree(_a) {
var rootElement = _a.rootElement, _b = _a.rootContext, rootContext = _b === void 0 ? {} : _b;
var promises = [];
walkTree(rootElement, rootContext, function (_, instance, context, childContext) {
if (instance && hasFetchDataFunction(instance)) {
var promise = instance.fetchData();
if (isPromise(promise)) {
promises.push({ promise: promise, context: childContext || context, instance: instance });
return false;
}
}
});
return promises;
}
function getDataFromTree(rootElement, rootContext) {
if (rootContext === void 0) { rootContext = {}; }
var promises = getPromisesFromTree({ rootElement: rootElement, rootContext: rootContext });
if (!promises.length) {
return Promise.resolve();
}
var errors = [];
var mappedPromises = promises.map(function (_a) {
var promise = _a.promise, context = _a.context, instance = _a.instance;
return promise
.then(function (_) { return getDataFromTree(instance.render(), context); })
.catch(function (e) { return errors.push(e); });
});
return Promise.all(mappedPromises).then(function (_) {
if (errors.length > 0) {
var error = errors.length === 1
? errors[0]
: new Error(errors.length + " errors were thrown when executing your fetchData functions.");
error.queryErrors = errors;
throw error;
}
});
}
var invariant = require('invariant');
var ApolloConsumer = function (props, context) {
invariant(!!context.client, "Could not find \"client\" in the context of ApolloConsumer. Wrap the root component in an <ApolloProvider>");
return props.children(context.client);
};
ApolloConsumer.contextTypes = {
client: PropTypes.object.isRequired,
};
ApolloConsumer.propTypes = {
children: PropTypes.func.isRequired,
};
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var invariant$1 = require('invariant');
var ApolloProvider = (function (_super) {
__extends(ApolloProvider, _super);
function ApolloProvider(props, context) {
var _this = _super.call(this, props, context) || this;
_this.operations = new Map();
invariant$1(props.client, 'ApolloClient was not passed a client instance. Make ' +
'sure you pass in your client via the "client" prop.');
if (!props.client.__operations_cache__) {
props.client.__operations_cache__ = _this.operations;
}
return _this;
}
ApolloProvider.prototype.getChildContext = function () {
return {
client: this.props.client,
operations: this.props.client.__operations_cache__,
};
};
ApolloProvider.prototype.render = function () {
return this.props.children;
};
ApolloProvider.propTypes = {
client: PropTypes.object.isRequired,
children: PropTypes.element.isRequired,
};
ApolloProvider.childContextTypes = {
client: PropTypes.object.isRequired,
operations: PropTypes.object,
};
return ApolloProvider;
}(React.Component));
var invariant$2 = require('invariant');
var DocumentType;
(function (DocumentType) {
DocumentType[DocumentType["Query"] = 0] = "Query";
DocumentType[DocumentType["Mutation"] = 1] = "Mutation";
DocumentType[DocumentType["Subscription"] = 2] = "Subscription";
})(DocumentType || (DocumentType = {}));
var cache = new Map();
function parser(document) {
var cached = cache.get(document);
if (cached)
return cached;
var variables, type, name;
invariant$2(!!document && !!document.kind, "Argument of " + document + " passed to parser was not a valid GraphQL " +
"DocumentNode. You may need to use 'graphql-tag' or another method " +
"to convert your operation into a document");
var fragments = document.definitions.filter(function (x) { return x.kind === 'FragmentDefinition'; });
var queries = document.definitions.filter(function (x) { return x.kind === 'OperationDefinition' && x.operation === 'query'; });
var mutations = document.definitions.filter(function (x) { return x.kind === 'OperationDefinition' && x.operation === 'mutation'; });
var subscriptions = document.definitions.filter(function (x) { return x.kind === 'OperationDefinition' && x.operation === 'subscription'; });
invariant$2(!fragments.length || (queries.length || mutations.length || subscriptions.length), "Passing only a fragment to 'graphql' is not yet supported. " +
"You must include a query, subscription or mutation as well");
invariant$2(queries.length + mutations.length + subscriptions.length <= 1, "react-apollo only supports a query, subscription, or a mutation per HOC. " +
(document + " had " + queries.length + " queries, " + subscriptions.length + " ") +
("subscriptions and " + mutations.length + " mutations. ") +
"You can use 'compose' to join multiple operation types to a component");
type = queries.length ? DocumentType.Query : DocumentType.Mutation;
if (!queries.length && !mutations.length)
type = DocumentType.Subscription;
var definitions = queries.length ? queries : mutations.length ? mutations : subscriptions;
invariant$2(definitions.length === 1, "react-apollo only supports one defintion per HOC. " + document + " had " +
(definitions.length + " definitions. ") +
"You can use 'compose' to join multiple operation types to a component");
var definition = definitions[0];
variables = definition.variableDefinitions || [];
if (definition.name && definition.name.kind === 'Name') {
name = definition.name.value;
}
else {
name = 'data';
}
var payload = { name: name, type: type, variables: variables };
cache.set(document, payload);
return payload;
}
var __extends$1 = (undefined && undefined.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var __rest = (undefined && undefined.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
t[p[i]] = s[p[i]];
return t;
};
var shallowEqual = require('fbjs/lib/shallowEqual');
var invariant$3 = require('invariant');
function compact(obj) {
return Object.keys(obj).reduce(function (acc, key) {
if (obj[key] !== undefined) {
acc[key] = obj[key];
}
return acc;
}, {});
}
function observableQueryFields(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;
}
var Query = (function (_super) {
__extends$1(Query, _super);
function Query(props, context) {
var _this = _super.call(this, props, context) || this;
_this.previousData = {};
_this.startQuerySubscription = function () {
if (_this.querySubscription)
return;
var current = _this.getQueryResult();
_this.querySubscription = _this.queryObservable.subscribe({
next: function () {
if (current && current.networkStatus === 7) {
current = undefined;
return;
}
_this.updateCurrentData();
},
error: function (error) {
_this.resubscribeToQuery();
if (!error.hasOwnProperty('graphQLErrors'))
throw error;
_this.updateCurrentData();
},
});
};
_this.removeQuerySubscription = function () {
if (_this.querySubscription) {
_this.querySubscription.unsubscribe();
delete _this.querySubscription;
}
};
_this.updateCurrentData = function () {
if (_this.hasMounted)
_this.forceUpdate();
};
_this.getQueryResult = function () {
var data = { data: Object.create(null) };
Object.assign(data, observableQueryFields(_this.queryObservable));
var currentResult = _this.queryObservable.currentResult();
var loading = currentResult.loading, networkStatus = currentResult.networkStatus, errors = currentResult.errors;
var error = currentResult.error;
if (errors && errors.length > 0) {
error = new apolloClient.ApolloError({ graphQLErrors: errors });
}
Object.assign(data, { loading: loading, networkStatus: networkStatus, error: error });
if (loading) {
Object.assign(data.data, _this.previousData, currentResult.data);
}
else if (error) {
Object.assign(data, {
data: (_this.queryObservable.getLastResult() || {}).data,
});
}
else {
Object.assign(data.data, currentResult.data);
_this.previousData = currentResult.data;
}
if (!_this.querySubscription) {
data.refetch = function (args) {
return new Promise(function (r, f) {
_this.refetcherQueue = { resolve: r, reject: f, args: args };
});
};
}
data.client = _this.client;
return data;
};
_this.client = props.client || context.client;
invariant$3(!!_this.client, "Could not find \"client\" in the context of Query or as passed props. Wrap the root component in an <ApolloProvider>");
_this.initializeQueryObservable(props);
return _this;
}
Query.prototype.fetchData = function () {
if (this.props.skip)
return false;
var _a = this.props, children = _a.children, ssr = _a.ssr, displayName = _a.displayName, skip = _a.skip, client = _a.client, opts = __rest(_a, ["children", "ssr", "displayName", "skip", "client"]);
var fetchPolicy = opts.fetchPolicy;
if (ssr === false)
return false;
if (fetchPolicy === 'network-only' || fetchPolicy === 'cache-and-network') {
fetchPolicy = 'cache-first';
}
var observable = this.client.watchQuery(__assign({}, opts, { fetchPolicy: fetchPolicy }));
var result = this.queryObservable.currentResult();
return result.loading ? observable.result() : false;
};
Query.prototype.componentDidMount = function () {
this.hasMounted = true;
if (this.props.skip)
return;
this.startQuerySubscription();
if (this.refetcherQueue) {
var _a = this.refetcherQueue, args = _a.args, resolve = _a.resolve, reject = _a.reject;
this.queryObservable.refetch(args)
.then(resolve)
.catch(reject);
}
};
Query.prototype.componentWillReceiveProps = function (nextProps, nextContext) {
if (nextProps.skip && !this.props.skip) {
this.removeQuerySubscription();
return;
}
var client = nextProps.client;
if (shallowEqual(this.props, nextProps) &&
(this.client === client || this.client === nextContext.client)) {
return;
}
if (this.client !== client && this.client !== nextContext.client) {
if (client) {
this.client = client;
}
else {
this.client = nextContext.client;
}
this.removeQuerySubscription();
this.queryObservable = null;
this.previousData = {};
this.updateQuery(nextProps);
}
if (this.props.query !== nextProps.query) {
this.removeQuerySubscription();
}
this.updateQuery(nextProps);
if (nextProps.skip)
return;
this.startQuerySubscription();
};
Query.prototype.componentWillUnmount = function () {
this.removeQuerySubscription();
this.hasMounted = false;
};
Query.prototype.render = function () {
var children = this.props.children;
var queryResult = this.getQueryResult();
return children(queryResult);
};
Query.prototype.extractOptsFromProps = function (props) {
var variables = props.variables, pollInterval = props.pollInterval, fetchPolicy = props.fetchPolicy, errorPolicy = props.errorPolicy, notifyOnNetworkStatusChange = props.notifyOnNetworkStatusChange, query = props.query, _a = props.displayName, displayName = _a === void 0 ? 'Query' : _a, _b = props.context, context = _b === void 0 ? {} : _b;
this.operation = parser(query);
invariant$3(this.operation.type === DocumentType.Query, "The <Query /> component requires a graphql query, but got a " + (this.operation.type === DocumentType.Mutation ? 'mutation' : 'subscription') + ".");
return compact({
variables: variables,
pollInterval: pollInterval,
query: query,
fetchPolicy: fetchPolicy,
errorPolicy: errorPolicy,
notifyOnNetworkStatusChange: notifyOnNetworkStatusChange,
metadata: { reactComponent: { displayName: displayName } },
context: context,
});
};
Query.prototype.initializeQueryObservable = function (props) {
var opts = this.extractOptsFromProps(props);
if (this.context.operations) {
this.context.operations.set(this.operation.name, {
query: opts.query,
variables: opts.variables,
});
}
this.queryObservable = this.client.watchQuery(opts);
};
Query.prototype.updateQuery = function (props) {
if (!this.queryObservable)
this.initializeQueryObservable(props);
this.queryObservable.setOptions(this.extractOptsFromProps(props))
.catch(function () { return null; });
};
Query.prototype.resubscribeToQuery = function () {
this.removeQuerySubscription();
var lastError = this.queryObservable.getLastError();
var lastResult = this.queryObservable.getLastResult();
this.queryObservable.resetLastResults();
this.startQuerySubscription();
Object.assign(this.queryObservable, { lastError: lastError, lastResult: lastResult });
};
Query.contextTypes = {
client: PropTypes.object.isRequired,
operations: PropTypes.object,
};
Query.propTypes = {
children: PropTypes.func.isRequired,
fetchPolicy: PropTypes.string,
notifyOnNetworkStatusChange: PropTypes.bool,
pollInterval: PropTypes.number,
query: PropTypes.object.isRequired,
variables: PropTypes.object,
ssr: PropTypes.bool,
};
return Query;
}(React.Component));
var __extends$2 = (undefined && undefined.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign$1 = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var invariant$4 = require('invariant');
var shallowEqual$1 = require('fbjs/lib/shallowEqual');
var initialState = {
loading: false,
called: false,
error: undefined,
data: undefined,
};
var Mutation = (function (_super) {
__extends$2(Mutation, _super);
function Mutation(props, context) {
var _this = _super.call(this, props, context) || this;
_this.runMutation = function (options) {
if (options === void 0) { options = {}; }
_this.onStartMutation();
var mutationId = _this.generateNewMutationId();
return _this.mutate(options)
.then(function (response) {
_this.onCompletedMutation(response, mutationId);
return response;
})
.catch(function (e) {
_this.onMutationError(e, mutationId);
if (!_this.props.onError)
throw e;
});
};
_this.mutate = function (options) {
var _a = _this.props, mutation = _a.mutation, variables = _a.variables, optimisticResponse = _a.optimisticResponse, update = _a.update, _b = _a.context, context = _b === void 0 ? {} : _b;
var refetchQueries = options.refetchQueries || _this.props.refetchQueries;
if (refetchQueries && refetchQueries.length && Array.isArray(refetchQueries)) {
refetchQueries = refetchQueries.map(function (x) {
if (typeof x === 'string' && _this.context.operations)
return _this.context.operations.get(x) || x;
return x;
});
delete options.refetchQueries;
}
return _this.client.mutate(__assign$1({ mutation: mutation,
variables: variables,
optimisticResponse: optimisticResponse,
refetchQueries: refetchQueries,
update: update,
context: context }, options));
};
_this.onStartMutation = function () {
if (!_this.state.loading && !_this.props.ignoreResults) {
_this.setState({
loading: true,
error: undefined,
data: undefined,
called: true,
});
}
};
_this.onCompletedMutation = function (response, mutationId) {
if (_this.hasMounted === false) {
return;
}
var _a = _this.props, onCompleted = _a.onCompleted, ignoreResults = _a.ignoreResults;
var data = response.data;
var callOncomplete = function () { return (onCompleted ? onCompleted(data) : null); };
if (_this.isMostRecentMutation(mutationId) && !ignoreResults) {
_this.setState({ loading: false, data: data }, callOncomplete);
}
else {
callOncomplete();
}
};
_this.onMutationError = function (error, mutationId) {
if (_this.hasMounted === false) {
return;
}
var onError = _this.props.onError;
var callOnError = function () { return (onError ? onError(error) : null); };
if (_this.isMostRecentMutation(mutationId)) {
_this.setState({ loading: false, error: error }, callOnError);
}
else {
callOnError();
}
};
_this.generateNewMutationId = function () {
_this.mostRecentMutationId = _this.mostRecentMutationId + 1;
return _this.mostRecentMutationId;
};
_this.isMostRecentMutation = function (mutationId) {
return _this.mostRecentMutationId === mutationId;
};
_this.verifyDocumentIsMutation = function (mutation) {
var operation = parser(mutation);
invariant$4(operation.type === DocumentType.Mutation, "The <Mutation /> component requires a graphql mutation, but got a " + (operation.type === DocumentType.Query ? 'query' : 'subscription') + ".");
};
_this.verifyContext = function (context) {
invariant$4(!!context.client, "Could not find \"client\" in the context of Mutation. Wrap the root component in an <ApolloProvider>");
};
_this.verifyContext(context);
_this.client = context.client;
_this.verifyDocumentIsMutation(props.mutation);
_this.mostRecentMutationId = 0;
_this.state = initialState;
return _this;
}
Mutation.prototype.componentDidMount = function () {
this.hasMounted = true;
};
Mutation.prototype.componentWillUnmount = function () {
this.hasMounted = false;
};
Mutation.prototype.componentWillReceiveProps = function (nextProps, nextContext) {
if (shallowEqual$1(this.props, nextProps) && this.client === nextContext.client) {
return;
}
if (this.props.mutation !== nextProps.mutation) {
this.verifyDocumentIsMutation(nextProps.mutation);
}
if (this.client !== nextContext.client) {
this.client = nextContext.client;
this.setState(initialState);
}
};
Mutation.prototype.render = function () {
var children = this.props.children;
var _a = this.state, loading = _a.loading, data = _a.data, error = _a.error, called = _a.called;
var result = {
called: called,
loading: loading,
data: data,
error: error,
};
return children(this.runMutation, result);
};
Mutation.contextTypes = {
client: PropTypes.object.isRequired,
operations: PropTypes.object,
};
Mutation.propTypes = {
mutation: PropTypes.object.isRequired,
variables: PropTypes.object,
optimisticResponse: PropTypes.object,
refetchQueries: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.string),
PropTypes.arrayOf(PropTypes.object),
PropTypes.func,
]),
update: PropTypes.func,
children: PropTypes.func.isRequired,
onCompleted: PropTypes.func,
onError: PropTypes.func,
};
return Mutation;
}(React.Component));
var __extends$3 = (undefined && undefined.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var shallowEqual$2 = require('fbjs/lib/shallowEqual');
var invariant$5 = require('invariant');
var Subscription = (function (_super) {
__extends$3(Subscription, _super);
function Subscription(props, context) {
var _this = _super.call(this, props, context) || this;
_this.initialize = function (props) {
if (_this.queryObservable)
return;
_this.queryObservable = _this.client.subscribe({
query: props.subscription,
variables: props.variables,
});
};
_this.startSubscription = function () {
if (_this.querySubscription)
return;
_this.querySubscription = _this.queryObservable.subscribe({
next: _this.updateCurrentData,
error: _this.updateError,
});
};
_this.getInitialState = function () { return ({
loading: true,
error: undefined,
data: undefined,
}); };
_this.updateCurrentData = function (result) {
_this.setState({
data: result.data,
loading: false,
error: undefined,
});
};
_this.updateError = function (error) {
_this.setState({
error: error,
loading: false,
});
};
_this.endSubscription = function () {
if (_this.querySubscription) {
_this.querySubscription.unsubscribe();
delete _this.querySubscription;
}
};
invariant$5(!!context.client, "Could not find \"client\" in the context of Subscription. Wrap the root component in an <ApolloProvider>");
_this.client = context.client;
_this.initialize(props);
_this.state = _this.getInitialState();
return _this;
}
Subscription.prototype.componentDidMount = function () {
this.startSubscription();
};
Subscription.prototype.componentWillReceiveProps = function (nextProps, nextContext) {
if (shallowEqual$2(this.props, nextProps) && this.client === nextContext.client) {
return;
}
var shouldNotResubscribe = this.props.shouldResubscribe === false;
if (this.client !== nextContext.client) {
this.client = nextContext.client;
}
if (!shouldNotResubscribe) {
this.endSubscription();
delete this.queryObservable;
this.initialize(nextProps);
this.startSubscription();
this.setState(this.getInitialState());
return;
}
this.initialize(nextProps);
this.startSubscription();
};
Subscription.prototype.componentWillUnmount = function () {
this.endSubscription();
};
Subscription.prototype.render = function () {
var result = Object.assign({}, this.state, {
variables: this.props.variables,
});
return this.props.children(result);
};
Subscription.contextTypes = {
client: PropTypes.object.isRequired,
};
Subscription.propTypes = {
subscription: PropTypes.object.isRequired,
variables: PropTypes.object,
children: PropTypes.func.isRequired,
};
return Subscription;
}(React.Component));
var __extends$4 = (undefined && undefined.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var invariant$6 = require('invariant');
var defaultMapPropsToOptions = function () { return ({}); };
var defaultMapPropsToSkip = function () { return false; };
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
function calculateVariablesFromProps(operation, props, graphQLDisplayName, wrapperName) {
var variables = {};
for (var _i = 0, _a = operation.variables; _i < _a.length; _i++) {
var _b = _a[_i], variable = _b.variable, type = _b.type;
if (!variable.name || !variable.name.value)
continue;
var variableName = variable.name.value;
var variableProp = props[variableName];
if (typeof variableProp !== 'undefined') {
variables[variableName] = variableProp;
continue;
}
if (type.kind !== 'NonNullType') {
variables[variableName] = null;
continue;
}
if (operation.type === DocumentType.Mutation)
return;
invariant$6(typeof variableProp !== 'undefined', "The operation '" + operation.name + "' wrapping '" + wrapperName + "' " +
("is expecting a variable: '" + variable.name.value + "' but it was not found in the props ") +
("passed to '" + graphQLDisplayName + "'"));
}
return variables;
}
var GraphQLBase = (function (_super) {
__extends$4(GraphQLBase, _super);
function GraphQLBase(props) {
var _this = _super.call(this, props) || this;
_this.setWrappedInstance = _this.setWrappedInstance.bind(_this);
return _this;
}
GraphQLBase.prototype.getWrappedInstance = function () {
invariant$6(this.withRef, "To access the wrapped instance, you need to specify " + "{ withRef: true } in the options");
return this.wrappedInstance;
};
GraphQLBase.prototype.setWrappedInstance = function (ref) {
this.wrappedInstance = ref;
};
return GraphQLBase;
}(React.Component));
var __extends$5 = (undefined && undefined.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign$2 = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var __rest$1 = (undefined && undefined.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
t[p[i]] = s[p[i]];
return t;
};
var hoistNonReactStatics = require('hoist-non-react-statics');
function query(document, operationOptions) {
if (operationOptions === void 0) { operationOptions = {}; }
var operation = parser(document);
var _a = operationOptions.options, options = _a === void 0 ? defaultMapPropsToOptions : _a, _b = operationOptions.skip, skip = _b === void 0 ? defaultMapPropsToSkip : _b, _c = operationOptions.alias, alias = _c === void 0 ? 'Apollo' : _c;
var mapPropsToOptions = options;
if (typeof mapPropsToOptions !== 'function')
mapPropsToOptions = function () { return options; };
var mapPropsToSkip = skip;
if (typeof mapPropsToSkip !== 'function')
mapPropsToSkip = function () { return skip; };
var lastResultProps;
return function (WrappedComponent) {
var graphQLDisplayName = alias + "(" + getDisplayName(WrappedComponent) + ")";
var GraphQL = (function (_super) {
__extends$5(GraphQL, _super);
function GraphQL() {
return _super !== null && _super.apply(this, arguments) || this;
}
GraphQL.prototype.render = function () {
var _this = this;
var props = this.props;
var shouldSkip = mapPropsToSkip(props);
var opts = shouldSkip ? Object.create(null) : mapPropsToOptions(props);
if (!shouldSkip && !opts.variables && operation.variables.length > 0) {
opts.variables = calculateVariablesFromProps(operation, props, graphQLDisplayName, getDisplayName(WrappedComponent));
}
return (React.createElement(Query, __assign$2({}, opts, { displayName: graphQLDisplayName, skip: shouldSkip, query: document, warnUnhandledError: true }), function (_a) {
var _ = _a.client, data = _a.data, r = __rest$1(_a, ["client", "data"]);
if (operationOptions.withRef) {
_this.withRef = true;
props = Object.assign({}, props, {
ref: _this.setWrappedInstance,
});
}
if (shouldSkip)
return React.createElement(WrappedComponent, __assign$2({}, props));
var result = Object.assign(r, data || {});
var name = operationOptions.name || 'data';
var childProps = (_b = {}, _b[name] = result, _b);
if (operationOptions.props) {
var newResult = (_c = {}, _c[name] = result, _c.ownProps = props, _c);
lastResultProps = operationOptions.props(newResult, lastResultProps);
childProps = lastResultProps;
}
return React.createElement(WrappedComponent, __assign$2({}, props, childProps));
var _b, _c;
}));
};
GraphQL.displayName = graphQLDisplayName;
GraphQL.WrappedComponent = WrappedComponent;
return GraphQL;
}(GraphQLBase));
return hoistNonReactStatics(GraphQL, WrappedComponent, {});
};
}
var __extends$6 = (undefined && undefined.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign$3 = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var hoistNonReactStatics$1 = require('hoist-non-react-statics');
function mutation(document, operationOptions) {
if (operationOptions === void 0) { operationOptions = {}; }
var operation = parser(document);
var _a = operationOptions.options, options = _a === void 0 ? defaultMapPropsToOptions : _a, _b = operationOptions.alias, alias = _b === void 0 ? 'Apollo' : _b;
var mapPropsToOptions = options;
if (typeof mapPropsToOptions !== 'function')
mapPropsToOptions = function () { return options; };
return function (WrappedComponent) {
var graphQLDisplayName = alias + "(" + getDisplayName(WrappedComponent) + ")";
var GraphQL = (function (_super) {
__extends$6(GraphQL, _super);
function GraphQL() {
return _super !== null && _super.apply(this, arguments) || this;
}
GraphQL.prototype.render = function () {
var props = this.props;
var opts = mapPropsToOptions(props);
if (operationOptions.withRef) {
this.withRef = true;
props = Object.assign({}, props, {
ref: this.setWrappedInstance,
});
}
if (!opts.variables && operation.variables.length > 0) {
opts.variables = calculateVariablesFromProps(operation, props, graphQLDisplayName, getDisplayName(WrappedComponent));
}
return (React.createElement(Mutation, __assign$3({}, opts, { mutation: document, ignoreResults: true }), function (mutate, _result) {
var name = operationOptions.name || 'mutate';
var childProps = (_a = {}, _a[name] = mutate, _a);
if (operationOptions.props) {
var newResult = (_b = {}, _b[name] = mutate, _b.ownProps = props, _b);
childProps = operationOptions.props(newResult);
}
return React.createElement(WrappedComponent, __assign$3({}, props, childProps));
var _a, _b;
}));
};
GraphQL.displayName = graphQLDisplayName;
GraphQL.WrappedComponent = WrappedComponent;
return GraphQL;
}(GraphQLBase));
return hoistNonReactStatics$1(GraphQL, WrappedComponent, {});
};
}
var __extends$7 = (undefined && undefined.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign$4 = (undefined && undefined.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var __rest$2 = (undefined && undefined.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
t[p[i]] = s[p[i]];
return t;
};
var hoistNonReactStatics$2 = require('hoist-non-react-statics');
function subscribe(document, operationOptions) {
if (operationOptions === void 0) { operationOptions = {}; }
var operation = parser(document);
var _a = operationOptions.options, options = _a === void 0 ? defaultMapPropsToOptions : _a, _b = operationOptions.skip, skip = _b === void 0 ? defaultMapPropsToSkip : _b, _c = operationOptions.alias, alias = _c === void 0 ? 'Apollo' : _c, shouldResubscribe = operationOptions.shouldResubscribe;
var mapPropsToOptions = options;
if (typeof mapPropsToOptions !== 'function')
mapPropsToOptions = function () { return options; };
var mapPropsToSkip = skip;
if (typeof mapPropsToSkip !== 'function')
mapPropsToSkip = function () { return skip; };
var lastResultProps;
return function (WrappedComponent) {
var graphQLDisplayName = alias + "(" + getDisplayName(WrappedComponent) + ")";
var GraphQL = (function (_super) {
__extends$7(GraphQL, _super);
function GraphQL(props) {
var _this = _super.call(this, props) || this;
_this.state = { resubscribe: false };
return _this;
}
GraphQL.prototype.componentWillReceiveProps = function (nextProps) {
if (!shouldResubscribe)
return;
this.setState({
resubscribe: shouldResubscribe(this.props, nextProps),
});
};
GraphQL.prototype.render = function () {
var _this = this;
var props = this.props;
var shouldSkip = mapPropsToSkip(props);
var opts = shouldSkip ? Object.create(null) : mapPropsToOptions(props);
if (!shouldSkip && !opts.variables && operation.variables.length > 0) {
opts.variables = calculateVariablesFromProps(operation, props, graphQLDisplayName, getDisplayName(WrappedComponent));
}
return (React.createElement(Subscription, __assign$4({}, opts, { displayName: graphQLDisplayName, skip: shouldSkip, subscription: document, shouldResubscribe: this.state.resubscribe }), function (_a) {
var data = _a.data, r = __rest$2(_a, ["data"]);
if (operationOptions.withRef) {
_this.withRef = true;
props = Object.assign({}, props, {
ref: _this.setWrappedInstance,
});
}
if (shouldSkip)
return React.createElement(WrappedComponent, __assign$4({}, props));
var result = Object.assign(r, data || {});
var name = operationOptions.name || 'data';
var childProps = (_b = {}, _b[name] = result, _b);
if (operationOptions.props) {
var newResult = (_c = {}, _c[name] = result, _c.ownProps = props, _c);
l