apollo-client
Version:
A simple yet functional GraphQL client.
1,323 lines (1,297 loc) • 116 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('whatwg-fetch'), require('graphql-tag/printer'), require('redux'), require('graphql-anywhere'), require('symbol-observable')) :
typeof define === 'function' && define.amd ? define(['exports', 'whatwg-fetch', 'graphql-tag/printer', 'redux', 'graphql-anywhere', 'symbol-observable'], factory) :
(factory((global.apollo = global.apollo || {}),null,global.graphqlTag_printer,global.redux,global.graphqlAnywhere,global.$$observable));
}(this, (function (exports,whatwgFetch,graphqlTag_printer,redux,graphqlAnywhere,$$observable) { 'use strict';
graphqlAnywhere = 'default' in graphqlAnywhere ? graphqlAnywhere['default'] : graphqlAnywhere;
$$observable = 'default' in $$observable ? $$observable['default'] : $$observable;
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;
};
function printRequest(request) {
return __assign({}, request, { query: graphqlTag_printer.print(request.query) });
}
var HTTPFetchNetworkInterface = (function () {
function HTTPFetchNetworkInterface(uri, opts) {
if (opts === void 0) { opts = {}; }
if (!uri) {
throw new Error('A remote endpoint is required for a network layer');
}
if (typeof uri !== 'string') {
throw new Error('Remote endpoint must be a string');
}
this._uri = uri;
this._opts = __assign({}, opts);
this._middlewares = [];
this._afterwares = [];
}
HTTPFetchNetworkInterface.prototype.applyMiddlewares = function (_a) {
var _this = this;
var request = _a.request, options = _a.options;
return new Promise(function (resolve, reject) {
var queue = function (funcs, scope) {
var next = function () {
if (funcs.length > 0) {
var f = funcs.shift();
if (f) {
f.applyMiddleware.apply(scope, [{ request: request, options: options }, next]);
}
}
else {
resolve({
request: request,
options: options,
});
}
};
next();
};
queue(_this._middlewares.slice(), _this);
});
};
HTTPFetchNetworkInterface.prototype.applyAfterwares = function (_a) {
var _this = this;
var response = _a.response, options = _a.options;
return new Promise(function (resolve, reject) {
var queue = function (funcs, scope) {
var next = function () {
if (funcs.length > 0) {
var f = funcs.shift();
f.applyAfterware.apply(scope, [{ response: response, options: options }, next]);
}
else {
resolve({
response: response,
options: options,
});
}
};
next();
};
queue(_this._afterwares.slice(), _this);
});
};
HTTPFetchNetworkInterface.prototype.fetchFromRemoteEndpoint = function (_a) {
var request = _a.request, options = _a.options;
return fetch(this._uri, __assign({}, this._opts, { body: JSON.stringify(printRequest(request)), method: 'POST' }, options, { headers: __assign({ Accept: '*/*', 'Content-Type': 'application/json' }, options.headers) }));
};
HTTPFetchNetworkInterface.prototype.query = function (request) {
var _this = this;
var options = __assign({}, this._opts);
return this.applyMiddlewares({
request: request,
options: options,
}).then(function (rao) { return _this.fetchFromRemoteEndpoint.call(_this, rao); })
.then(function (response) { return _this.applyAfterwares({
response: response,
options: options,
}); })
.then(function (_a) {
var response = _a.response;
var httpResponse = response;
if (!httpResponse.ok) {
var httpError = new Error("Network request failed with status " + response.status + " - \"" + response.statusText + "\"");
httpError.response = httpResponse;
throw httpError;
}
return httpResponse.json();
})
.then(function (payload) {
if (!payload.hasOwnProperty('data') && !payload.hasOwnProperty('errors')) {
throw new Error("Server response was missing for query '" + request.debugName + "'.");
}
else {
return payload;
}
});
};
HTTPFetchNetworkInterface.prototype.use = function (middlewares) {
var _this = this;
middlewares.map(function (middleware) {
if (typeof middleware.applyMiddleware === 'function') {
_this._middlewares.push(middleware);
}
else {
throw new Error('Middleware must implement the applyMiddleware function');
}
});
return this;
};
HTTPFetchNetworkInterface.prototype.useAfter = function (afterwares) {
var _this = this;
afterwares.map(function (afterware) {
if (typeof afterware.applyAfterware === 'function') {
_this._afterwares.push(afterware);
}
else {
throw new Error('Afterware must implement the applyAfterware function');
}
});
return this;
};
return HTTPFetchNetworkInterface;
}());
function createNetworkInterface(uriOrInterfaceOpts, secondArgOpts) {
if (secondArgOpts === void 0) { secondArgOpts = {}; }
if (!uriOrInterfaceOpts) {
throw new Error('You must pass an options argument to createNetworkInterface.');
}
var uri;
var opts;
if (typeof uriOrInterfaceOpts === 'string') {
console.warn("Passing the URI as the first argument to createNetworkInterface is deprecated as of Apollo Client 0.5. Please pass it as the \"uri\" property of the network interface options.");
opts = secondArgOpts;
uri = uriOrInterfaceOpts;
}
else {
opts = uriOrInterfaceOpts.opts;
uri = uriOrInterfaceOpts.uri;
}
return new HTTPFetchNetworkInterface(uri, opts);
}
var QueryBatcher = (function () {
function QueryBatcher(_a) {
var batchFetchFunction = _a.batchFetchFunction;
this.queuedRequests = [];
this.queuedRequests = [];
this.batchFetchFunction = batchFetchFunction;
}
QueryBatcher.prototype.enqueueRequest = function (request) {
var fetchRequest = {
request: request,
};
this.queuedRequests.push(fetchRequest);
fetchRequest.promise = new Promise(function (resolve, reject) {
fetchRequest.resolve = resolve;
fetchRequest.reject = reject;
});
return fetchRequest.promise;
};
QueryBatcher.prototype.consumeQueue = function () {
if (this.queuedRequests.length < 1) {
return undefined;
}
var requests = this.queuedRequests.map(function (queuedRequest) {
return {
query: queuedRequest.request.query,
variables: queuedRequest.request.variables,
operationName: queuedRequest.request.operationName,
};
});
var promises = [];
var resolvers = [];
var rejecters = [];
this.queuedRequests.forEach(function (fetchRequest, index) {
promises.push(fetchRequest.promise);
resolvers.push(fetchRequest.resolve);
rejecters.push(fetchRequest.reject);
});
this.queuedRequests = [];
var batchedPromise = this.batchFetchFunction(requests);
batchedPromise.then(function (results) {
results.forEach(function (result, index) {
resolvers[index](result);
});
}).catch(function (error) {
rejecters.forEach(function (rejecter, index) {
rejecters[index](error);
});
});
return promises;
};
QueryBatcher.prototype.start = function (pollInterval) {
var _this = this;
if (this.pollTimer) {
clearInterval(this.pollTimer);
}
this.pollInterval = pollInterval;
this.pollTimer = setInterval(function () {
_this.consumeQueue();
}, this.pollInterval);
};
QueryBatcher.prototype.stop = function () {
if (this.pollTimer) {
clearInterval(this.pollTimer);
}
};
return QueryBatcher;
}());
function assign(target) {
var sources = [];
for (var _i = 1; _i < arguments.length; _i++) {
sources[_i - 1] = arguments[_i];
}
sources.forEach(function (source) { return Object.keys(source).forEach(function (key) {
target[key] = source[key];
}); });
return target;
}
var __extends = (undefined && undefined.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
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 HTTPBatchedNetworkInterface = (function (_super) {
__extends(HTTPBatchedNetworkInterface, _super);
function HTTPBatchedNetworkInterface(uri, pollInterval, fetchOpts) {
var _this = _super.call(this, uri, fetchOpts) || this;
if (typeof pollInterval !== 'number') {
throw new Error("pollInterval must be a number, got " + pollInterval);
}
_this.pollInterval = pollInterval;
_this.batcher = new QueryBatcher({
batchFetchFunction: _this.batchQuery.bind(_this),
});
_this.batcher.start(_this.pollInterval);
return _this;
}
HTTPBatchedNetworkInterface.prototype.query = function (request) {
return this.batcher.enqueueRequest(request);
};
HTTPBatchedNetworkInterface.prototype.batchQuery = function (requests) {
var _this = this;
var options = __assign$1({}, this._opts);
var middlewarePromises = [];
requests.forEach(function (request) {
middlewarePromises.push(_this.applyMiddlewares({
request: request,
options: options,
}));
});
return new Promise(function (resolve, reject) {
Promise.all(middlewarePromises).then(function (requestsAndOptions) {
return _this.batchedFetchFromRemoteEndpoint(requestsAndOptions)
.then(function (result) {
var httpResponse = result;
if (!httpResponse.ok) {
var httpError = new Error("Network request failed with status " + httpResponse.status + " - \"" + httpResponse.statusText + "\"");
httpError.response = httpResponse;
throw httpError;
}
return result.json();
})
.then(function (responses) {
if (typeof responses.map !== 'function') {
throw new Error('BatchingNetworkInterface: server response is not an array');
}
var afterwaresPromises = responses.map(function (response, index) {
return _this.applyAfterwares({
response: response,
options: requestsAndOptions[index].options,
});
});
Promise.all(afterwaresPromises).then(function (responsesAndOptions) {
var results = [];
responsesAndOptions.forEach(function (result) {
results.push(result.response);
});
resolve(results);
}).catch(function (error) {
reject(error);
});
});
}).catch(function (error) {
reject(error);
});
});
};
HTTPBatchedNetworkInterface.prototype.batchedFetchFromRemoteEndpoint = function (requestsAndOptions) {
var options = {};
requestsAndOptions.forEach(function (requestAndOptions) {
assign(options, requestAndOptions.options);
});
var printedRequests = requestsAndOptions.map(function (_a) {
var request = _a.request;
return printRequest(request);
});
return fetch(this._uri, __assign$1({}, this._opts, { body: JSON.stringify(printedRequests), method: 'POST' }, options, { headers: __assign$1({ Accept: '*/*', 'Content-Type': 'application/json' }, options.headers) }));
};
return HTTPBatchedNetworkInterface;
}(HTTPFetchNetworkInterface));
function createBatchingNetworkInterface(options) {
if (!options) {
throw new Error('You must pass an options argument to createNetworkInterface.');
}
return new HTTPBatchedNetworkInterface(options.uri, options.batchInterval, options.opts || {});
}
function isQueryResultAction(action) {
return action.type === 'APOLLO_QUERY_RESULT';
}
function isQueryErrorAction(action) {
return action.type === 'APOLLO_QUERY_ERROR';
}
function isQueryInitAction(action) {
return action.type === 'APOLLO_QUERY_INIT';
}
function isQueryResultClientAction(action) {
return action.type === 'APOLLO_QUERY_RESULT_CLIENT';
}
function isQueryStopAction(action) {
return action.type === 'APOLLO_QUERY_STOP';
}
function isMutationInitAction(action) {
return action.type === 'APOLLO_MUTATION_INIT';
}
function isMutationResultAction(action) {
return action.type === 'APOLLO_MUTATION_RESULT';
}
function isMutationErrorAction(action) {
return action.type === 'APOLLO_MUTATION_ERROR';
}
function isUpdateQueryResultAction(action) {
return action.type === 'APOLLO_UPDATE_QUERY_RESULT';
}
function isStoreResetAction(action) {
return action.type === 'APOLLO_STORE_RESET';
}
function isSubscriptionResultAction(action) {
return action.type === 'APOLLO_SUBSCRIPTION_RESULT';
}
function checkDocument(doc) {
if (doc.kind !== 'Document') {
throw new Error("Expecting a parsed GraphQL document. Perhaps you need to wrap the query string in a \"gql\" tag? http://docs.apollostack.com/apollo-client/core.html#gql");
}
var foundOperation = false;
doc.definitions.forEach(function (definition) {
switch (definition.kind) {
case 'FragmentDefinition':
break;
case 'OperationDefinition':
if (foundOperation) {
throw new Error('Queries must have exactly one operation definition.');
}
foundOperation = true;
break;
default:
throw new Error("Schema type definitions not allowed in queries. Found: \"" + definition.kind + "\"");
}
});
}
function getOperationName(doc) {
var res = '';
doc.definitions.forEach(function (definition) {
if (definition.kind === 'OperationDefinition' && definition.name) {
res = definition.name.value;
}
});
return res;
}
function getFragmentDefinitions(doc) {
var fragmentDefinitions = doc.definitions.filter(function (definition) {
if (definition.kind === 'FragmentDefinition') {
return true;
}
else {
return false;
}
});
return fragmentDefinitions;
}
function getQueryDefinition(doc) {
checkDocument(doc);
var queryDef = null;
doc.definitions.map(function (definition) {
if (definition.kind === 'OperationDefinition'
&& definition.operation === 'query') {
queryDef = definition;
}
});
if (!queryDef) {
throw new Error('Must contain a query definition.');
}
return queryDef;
}
function getOperationDefinition(doc) {
checkDocument(doc);
var opDef = null;
doc.definitions.map(function (definition) {
if (definition.kind === 'OperationDefinition') {
opDef = definition;
}
});
if (!opDef) {
throw new Error('Must contain a query definition.');
}
return opDef;
}
function createFragmentMap(fragments) {
if (fragments === void 0) { fragments = []; }
var symTable = {};
fragments.forEach(function (fragment) {
symTable[fragment.name.value] = fragment;
});
return symTable;
}
function isStringValue(value) {
return value.kind === 'StringValue';
}
function isBooleanValue(value) {
return value.kind === 'BooleanValue';
}
function isIntValue(value) {
return value.kind === 'IntValue';
}
function isFloatValue(value) {
return value.kind === 'FloatValue';
}
function isVariable(value) {
return value.kind === 'Variable';
}
function isObjectValue(value) {
return value.kind === 'ObjectValue';
}
function isListValue(value) {
return value.kind === 'ListValue';
}
function isEnumValue(value) {
return value.kind === 'EnumValue';
}
function valueToObjectRepresentation(argObj, name, value, variables) {
if (isIntValue(value) || isFloatValue(value)) {
argObj[name.value] = Number(value.value);
}
else if (isBooleanValue(value) || isStringValue(value)) {
argObj[name.value] = value.value;
}
else if (isObjectValue(value)) {
var nestedArgObj_1 = {};
value.fields.map(function (obj) { return valueToObjectRepresentation(nestedArgObj_1, obj.name, obj.value, variables); });
argObj[name.value] = nestedArgObj_1;
}
else if (isVariable(value)) {
var variableValue = (variables || {})[value.name.value];
argObj[name.value] = variableValue;
}
else if (isListValue(value)) {
argObj[name.value] = value.values.map(function (listValue) {
var nestedArgArrayObj = {};
valueToObjectRepresentation(nestedArgArrayObj, name, listValue, variables);
return nestedArgArrayObj[name.value];
});
}
else if (isEnumValue(value)) {
argObj[name.value] = value.value;
}
else {
throw new Error("The inline argument \"" + name.value + "\" of kind \"" + value.kind + "\" is not supported.\n Use variables instead of inline arguments to overcome this limitation.");
}
}
function storeKeyNameFromField(field, variables) {
if (field.arguments && field.arguments.length) {
var argObj_1 = {};
field.arguments.forEach(function (_a) {
var name = _a.name, value = _a.value;
return valueToObjectRepresentation(argObj_1, name, value, variables);
});
return storeKeyNameFromFieldNameAndArgs(field.name.value, argObj_1);
}
return field.name.value;
}
function storeKeyNameFromFieldNameAndArgs(fieldName, args) {
if (args) {
var stringifiedArgs = JSON.stringify(args);
return fieldName + "(" + stringifiedArgs + ")";
}
return fieldName;
}
function resultKeyNameFromField(field) {
return field.alias ?
field.alias.value :
field.name.value;
}
function isField(selection) {
return selection.kind === 'Field';
}
function isInlineFragment(selection) {
return selection.kind === 'InlineFragment';
}
function graphQLResultHasError(result) {
return result.errors && result.errors.length;
}
function isIdValue(idObject) {
return (idObject != null &&
typeof idObject === 'object' &&
idObject.type === 'id');
}
function toIdValue(id, generated) {
if (generated === void 0) { generated = false; }
return {
type: 'id',
id: id,
generated: generated,
};
}
function isJsonValue(jsonObject) {
return (jsonObject != null &&
typeof jsonObject === 'object' &&
jsonObject.type === 'json');
}
function shouldInclude(selection, variables) {
if (variables === void 0) { variables = {}; }
if (!selection.directives) {
return true;
}
var res = true;
selection.directives.forEach(function (directive) {
if (directive.name.value !== 'skip' && directive.name.value !== 'include') {
return;
}
var directiveArguments = directive.arguments || [];
var directiveName = directive.name.value;
if (directiveArguments.length !== 1) {
throw new Error("Incorrect number of arguments for the @" + directiveName + " directive.");
}
var ifArgument = directiveArguments[0];
if (!ifArgument.name || ifArgument.name.value !== 'if') {
throw new Error("Invalid argument for the @" + directiveName + " directive.");
}
var ifValue = directiveArguments[0].value;
var evaledValue = false;
if (!ifValue || ifValue.kind !== 'BooleanValue') {
if (ifValue.kind !== 'Variable') {
throw new Error("Argument for the @" + directiveName + " directive must be a variable or a bool ean value.");
}
else {
evaledValue = variables[ifValue.name.value];
if (evaledValue === undefined) {
throw new Error("Invalid variable referenced in @" + directiveName + " directive.");
}
}
}
else {
evaledValue = ifValue.value;
}
if (directiveName === 'skip') {
evaledValue = !evaledValue;
}
if (!evaledValue) {
res = false;
}
});
return res;
}
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;
};
function writeQueryToStore(_a) {
var result = _a.result, query = _a.query, _b = _a.store, store = _b === void 0 ? {} : _b, variables = _a.variables, dataIdFromObject = _a.dataIdFromObject, _c = _a.fragmentMap, fragmentMap = _c === void 0 ? {} : _c;
var queryDefinition = getQueryDefinition(query);
return writeSelectionSetToStore({
dataId: 'ROOT_QUERY',
result: result,
selectionSet: queryDefinition.selectionSet,
context: {
store: store,
variables: variables,
dataIdFromObject: dataIdFromObject,
fragmentMap: fragmentMap,
},
});
}
function writeResultToStore(_a) {
var result = _a.result, dataId = _a.dataId, document = _a.document, _b = _a.store, store = _b === void 0 ? {} : _b, variables = _a.variables, dataIdFromObject = _a.dataIdFromObject;
var selectionSet = getOperationDefinition(document).selectionSet;
var fragmentMap = createFragmentMap(getFragmentDefinitions(document));
return writeSelectionSetToStore({
result: result,
dataId: dataId,
selectionSet: selectionSet,
context: {
store: store,
variables: variables,
dataIdFromObject: dataIdFromObject,
fragmentMap: fragmentMap,
},
});
}
function writeSelectionSetToStore(_a) {
var result = _a.result, dataId = _a.dataId, selectionSet = _a.selectionSet, context = _a.context;
var variables = context.variables, store = context.store, dataIdFromObject = context.dataIdFromObject, fragmentMap = context.fragmentMap;
selectionSet.selections.forEach(function (selection) {
var included = shouldInclude(selection, variables);
if (isField(selection)) {
var resultFieldKey = resultKeyNameFromField(selection);
var value = result[resultFieldKey];
if (value !== undefined) {
writeFieldToStore({
dataId: dataId,
value: value,
field: selection,
context: context,
});
}
}
else if (isInlineFragment(selection)) {
if (included) {
writeSelectionSetToStore({
result: result,
selectionSet: selection.selectionSet,
dataId: dataId,
context: context,
});
}
}
else {
var fragment = void 0;
if (isInlineFragment(selection)) {
fragment = selection;
}
else {
fragment = (fragmentMap || {})[selection.name.value];
if (!fragment) {
throw new Error("No fragment named " + selection.name.value + ".");
}
}
if (included) {
writeSelectionSetToStore({
result: result,
selectionSet: fragment.selectionSet,
dataId: dataId,
context: context,
});
}
}
});
return store;
}
function isGeneratedId(id) {
return (id[0] === '$');
}
function mergeWithGenerated(generatedKey, realKey, cache) {
var generated = cache[generatedKey];
var real = cache[realKey];
Object.keys(generated).forEach(function (key) {
var value = generated[key];
var realValue = real[key];
if (isIdValue(value)
&& isGeneratedId(value.id)
&& isIdValue(realValue)) {
mergeWithGenerated(value.id, realValue.id, cache);
}
delete cache[generatedKey];
cache[realKey] = __assign$4({}, generated, real);
});
}
function writeFieldToStore(_a) {
var field = _a.field, value = _a.value, dataId = _a.dataId, context = _a.context;
var variables = context.variables, dataIdFromObject = context.dataIdFromObject, store = context.store, fragmentMap = context.fragmentMap;
var storeValue;
var storeFieldName = storeKeyNameFromField(field, variables);
var shouldMerge = false;
var generatedKey = '';
if (!field.selectionSet || value === null) {
storeValue =
value != null && typeof value === 'object'
? { type: 'json', json: value }
: value;
}
else if (Array.isArray(value)) {
var generatedId = dataId + "." + storeFieldName;
storeValue = processArrayValue(value, generatedId, field.selectionSet, context);
}
else {
var valueDataId = dataId + "." + storeFieldName;
var generated = true;
if (!isGeneratedId(valueDataId)) {
valueDataId = '$' + valueDataId;
}
if (dataIdFromObject) {
var semanticId = dataIdFromObject(value);
if (semanticId && isGeneratedId(semanticId)) {
throw new Error('IDs returned by dataIdFromObject cannot begin with the "$" character.');
}
if (semanticId) {
valueDataId = semanticId;
generated = false;
}
}
writeSelectionSetToStore({
dataId: valueDataId,
result: value,
selectionSet: field.selectionSet,
context: context,
});
storeValue = {
type: 'id',
id: valueDataId,
generated: generated,
};
if (store[dataId] && store[dataId][storeFieldName] !== storeValue) {
var escapedId = store[dataId][storeFieldName];
if (isIdValue(storeValue) && storeValue.generated
&& isIdValue(escapedId) && !escapedId.generated) {
throw new Error("Store error: the application attempted to write an object with no provided id" +
(" but the store already contains an id of " + escapedId.id + " for this object."));
}
if (isIdValue(escapedId) && escapedId.generated) {
generatedKey = escapedId.id;
shouldMerge = true;
}
}
}
var newStoreObj = __assign$4({}, store[dataId], (_b = {}, _b[storeFieldName] = storeValue, _b));
if (shouldMerge) {
mergeWithGenerated(generatedKey, storeValue.id, store);
}
if (!store[dataId] || storeValue !== store[dataId][storeFieldName]) {
store[dataId] = newStoreObj;
}
var _b;
}
function processArrayValue(value, generatedId, selectionSet, context) {
return value.map(function (item, index) {
if (item === null) {
return null;
}
var itemDataId = generatedId + "." + index;
if (Array.isArray(item)) {
return processArrayValue(item, itemDataId, selectionSet, context);
}
var generated = true;
if (context.dataIdFromObject) {
var semanticId = context.dataIdFromObject(item);
if (semanticId) {
itemDataId = semanticId;
generated = false;
}
}
writeSelectionSetToStore({
dataId: itemDataId,
result: item,
selectionSet: selectionSet,
context: context,
});
var idStoreValue = {
type: 'id',
id: itemDataId,
generated: generated,
};
return idStoreValue;
});
}
var __assign$5 = (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;
};
function replaceQueryResults(state, _a, config) {
var variables = _a.variables, document = _a.document, newResult = _a.newResult;
var clonedState = __assign$5({}, state);
return writeResultToStore({
result: newResult,
dataId: 'ROOT_QUERY',
variables: variables,
document: document,
store: clonedState,
dataIdFromObject: config.dataIdFromObject,
});
}
function isEqual(a, b) {
if (a === b) {
return true;
}
if (a != null && typeof a === 'object' && b != null && typeof b === 'object') {
for (var key in a) {
if (a.hasOwnProperty(key)) {
if (!b.hasOwnProperty(key)) {
return false;
}
if (!isEqual(a[key], b[key])) {
return false;
}
}
}
for (var key in b) {
if (!a.hasOwnProperty(key)) {
return false;
}
}
return true;
}
return false;
}
function getEnv() {
if (typeof process !== 'undefined' && process.env.NODE_ENV) {
return process.env.NODE_ENV;
}
return 'development';
}
function isEnv(env) {
return getEnv() === env;
}
function isProduction() {
return isEnv('production') === true;
}
function isDevelopment() {
return isEnv('development') === true;
}
function isTest() {
return isEnv('test') === true;
}
var __assign$6 = (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 ID_KEY = typeof Symbol !== 'undefined' ? Symbol('id') : '@@id';
function readQueryFromStore(options) {
var optsPatch = {
returnPartialData: ((options.returnPartialData !== undefined) ? options.returnPartialData : false),
};
return diffQueryAgainstStore(__assign$6({}, options, optsPatch)).result;
}
var haveWarned = false;
var fragmentMatcher = function (idValue, typeCondition, context) {
assertIdValue(idValue);
var obj = context.store[idValue.id];
if (!obj) {
return false;
}
if (!obj.__typename) {
if (!haveWarned) {
console.warn("You're using fragments in your queries, but don't have the addTypename:\ntrue option set in Apollo Client. Please turn on that option so that we can accurately\nmatch fragments.");
if (!isTest()) {
haveWarned = true;
}
}
context.returnPartialData = true;
return true;
}
if (obj.__typename === typeCondition) {
return true;
}
context.returnPartialData = true;
return true;
};
var readStoreResolver = function (fieldName, idValue, args, context, _a) {
var resultKey = _a.resultKey;
assertIdValue(idValue);
var objId = idValue.id;
var obj = context.store[objId];
var storeKeyName = storeKeyNameFromFieldNameAndArgs(fieldName, args);
var fieldValue = (obj || {})[storeKeyName];
if (typeof fieldValue === 'undefined') {
if (context.customResolvers && obj && (obj.__typename || objId === 'ROOT_QUERY')) {
var typename = obj.__typename || 'Query';
var type = context.customResolvers[typename];
if (type) {
var resolver = type[fieldName];
if (resolver) {
return resolver(obj, args);
}
}
}
if (!context.returnPartialData) {
throw new Error("Can't find field " + storeKeyName + " on object (" + objId + ") " + JSON.stringify(obj, null, 2) + ".\nPerhaps you want to use the `returnPartialData` option?");
}
context.hasMissingField = true;
return fieldValue;
}
if (isJsonValue(fieldValue)) {
if (idValue.previousResult && isEqual(idValue.previousResult[resultKey], fieldValue.json)) {
return idValue.previousResult[resultKey];
}
return fieldValue.json;
}
if (idValue.previousResult) {
fieldValue = addPreviousResultToIdValues(fieldValue, idValue.previousResult[resultKey]);
}
return fieldValue;
};
function diffQueryAgainstStore(_a) {
var store = _a.store, query = _a.query, variables = _a.variables, _b = _a.returnPartialData, returnPartialData = _b === void 0 ? true : _b, previousResult = _a.previousResult, config = _a.config;
getQueryDefinition(query);
var context = {
store: store,
returnPartialData: returnPartialData,
customResolvers: (config && config.customResolvers) || {},
hasMissingField: false,
};
var rootIdValue = {
type: 'id',
id: 'ROOT_QUERY',
previousResult: previousResult,
};
var result = graphqlAnywhere(readStoreResolver, query, rootIdValue, context, variables, {
fragmentMatcher: fragmentMatcher,
resultMapper: resultMapper,
});
return {
result: result,
isMissing: context.hasMissingField,
};
}
function assertIdValue(idValue) {
if (!isIdValue(idValue)) {
throw new Error("Encountered a sub-selection on the query, but the store doesn't have an object reference. This should never happen during normal use unless you have custom code that is directly manipulating the store; please file an issue.");
}
}
function addPreviousResultToIdValues(value, previousResult) {
if (isIdValue(value)) {
return __assign$6({}, value, { previousResult: previousResult });
}
else if (Array.isArray(value)) {
var idToPreviousResult_1 = {};
if (Array.isArray(previousResult)) {
previousResult.forEach(function (item) {
if (item[ID_KEY]) {
idToPreviousResult_1[item[ID_KEY]] = item;
}
});
}
return value.map(function (item, i) {
var itemPreviousResult = previousResult && previousResult[i];
if (isIdValue(item)) {
itemPreviousResult = idToPreviousResult_1[item.id] || itemPreviousResult;
}
return addPreviousResultToIdValues(item, itemPreviousResult);
});
}
return value;
}
function resultMapper(resultFields, idValue) {
if (idValue.previousResult) {
var currentResultKeys_1 = Object.keys(resultFields);
var sameAsPreviousResult = Object.keys(idValue.previousResult)
.reduce(function (sameKeys, key) { return sameKeys && currentResultKeys_1.indexOf(key) > -1; }, true) &&
currentResultKeys_1.reduce(function (same, key) { return (same && areNestedArrayItemsStrictlyEqual(resultFields[key], idValue.previousResult[key])); }, true);
if (sameAsPreviousResult) {
return idValue.previousResult;
}
}
Object.defineProperty(resultFields, ID_KEY, {
enumerable: false,
configurable: false,
writable: false,
value: idValue.id,
});
return resultFields;
}
function areNestedArrayItemsStrictlyEqual(a, b) {
if (a === b) {
return true;
}
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) {
return false;
}
return a.reduce(function (same, item, i) { return same && areNestedArrayItemsStrictlyEqual(item, b[i]); }, true);
}
function tryFunctionOrLogError(f) {
try {
return f();
}
catch (e) {
if (console.error) {
console.error(e);
}
}
}
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;
};
function data(previousState, action, queries, mutations, config) {
if (previousState === void 0) { previousState = {}; }
var constAction = action;
if (isQueryResultAction(action)) {
if (!queries[action.queryId]) {
return previousState;
}
if (action.requestId < queries[action.queryId].lastRequestId) {
return previousState;
}
if (!graphQLResultHasError(action.result)) {
var queryStoreValue = queries[action.queryId];
var clonedState = __assign$3({}, previousState);
var newState_1 = writeResultToStore({
result: action.result.data,
dataId: 'ROOT_QUERY',
document: action.document,
variables: queryStoreValue.variables,
store: clonedState,
dataIdFromObject: config.dataIdFromObject,
});
if (action.extraReducers) {
action.extraReducers.forEach(function (reducer) {
newState_1 = reducer(newState_1, constAction);
});
}
return newState_1;
}
}
else if (isSubscriptionResultAction(action)) {
if (!graphQLResultHasError(action.result)) {
var clonedState = __assign$3({}, previousState);
var newState_2 = writeResultToStore({
result: action.result.data,
dataId: 'ROOT_SUBSCRIPTION',
document: action.document,
variables: action.variables,
store: clonedState,
dataIdFromObject: config.dataIdFromObject,
});
if (action.extraReducers) {
action.extraReducers.forEach(function (reducer) {
newState_2 = reducer(newState_2, constAction);
});
}
return newState_2;
}
}
else if (isMutationResultAction(constAction)) {
if (!constAction.result.errors) {
var queryStoreValue = mutations[constAction.mutationId];
var clonedState = __assign$3({}, previousState);
var newState_3 = writeResultToStore({
result: constAction.result.data,
dataId: 'ROOT_MUTATION',
document: constAction.document,
variables: queryStoreValue.variables,
store: clonedState,
dataIdFromObject: config.dataIdFromObject,
});
var updateQueries_1 = constAction.updateQueries;
if (updateQueries_1) {
Object.keys(updateQueries_1).forEach(function (queryId) {
var query = queries[queryId];
if (!query) {
return;
}
var currentQueryResult = readQueryFromStore({
store: previousState,
query: query.document,
variables: query.variables,
returnPartialData: true,
config: config,
});
var reducer = updateQueries_1[queryId];
var nextQueryResult = tryFunctionOrLogError(function () { return reducer(currentQueryResult, {
mutationResult: constAction.result,
queryName: getOperationName(query.document),
queryVariables: query.variables,
}); });
if (nextQueryResult) {
newState_3 = writeResultToStore({
result: nextQueryResult,
dataId: 'ROOT_QUERY',
document: query.document,
variables: query.variables,
store: newState_3,
dataIdFromObject: config.dataIdFromObject,
});
}
});
}
if (constAction.extraReducers) {
constAction.extraReducers.forEach(function (reducer) {
newState_3 = reducer(newState_3, constAction);
});
}
return newState_3;
}
}
else if (isUpdateQueryResultAction(constAction)) {
return replaceQueryResults(previousState, constAction, config);
}
else if (isStoreResetAction(action)) {
return {};
}
return previousState;
}
(function (NetworkStatus) {
NetworkStatus[NetworkStatus["loading"] = 1] = "loading";
NetworkStatus[NetworkStatus["setVariables"] = 2] = "setVariables";
NetworkStatus[NetworkStatus["fetchMore"] = 3] = "fetchMore";
NetworkStatus[NetworkStatus["refetch"] = 4] = "refetch";
NetworkStatus[NetworkStatus["poll"] = 6] = "poll";
NetworkStatus[NetworkStatus["ready"] = 7] = "ready";
NetworkStatus[NetworkStatus["error"] = 8] = "error";
})(exports.NetworkStatus || (exports.NetworkStatus = {}));
function isNetworkRequestInFlight(networkStatus) {
return networkStatus < 7;
}
var __assign$7 = (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;
};
function queries(previousState, action) {
if (previousState === void 0) { previousState = {}; }
if (isQueryInitAction(action)) {
var newState = __assign$7({}, previousState);
var previousQuery = previousState[action.queryId];
if (previousQuery && previousQuery.queryString !== action.queryString) {
throw new Error('Internal Error: may not update existing query string in store');
}
var isSetVariables = false;
var previousVariables = null;
if (action.storePreviousVariables &&
previousQuery &&
previousQuery.networkStatus !== exports.NetworkStatus.loading) {
if (!isEqual(previousQuery.variables, action.variables)) {
isSetVariables = true;
previousVariables = previousQuery.variables;
}
}
var newNetworkStatus = exports.NetworkStatus.loading;
if (isSetVariables) {
newNetworkStatus = exports.NetworkStatus.setVariables;
}
else if (action.isPoll) {
newNetworkStatus = exports.NetworkStatus.poll;
}
else if (action.isRefetch) {
newNetworkStatus = exports.NetworkStatus.refetch;
}
else if (action.isPoll) {
newNetworkStatus = exports.NetworkStatus.poll;
}
newState[action.queryId] = {
queryString: action.queryString,
document: action.document,
variables: action.variables,
previousVariables: previousVariables,
networkError: null,
graphQLErrors: [],
networkStatus: newNetworkStatus,
forceFetch: action.forceFetch,
returnPartialData: action.returnPartialData,
lastRequestId: action.requestId,
metadata: action.metadata,
};
return newState;
}
else if (isQueryResultAction(action)) {
if (!previousState[action.queryId]) {
return previousState;
}
if (action.requestId < previousState[action.queryId].lastRequestId) {
return previousState;
}
var newState = __assign$7({}, previousState);
var resultHasGraphQLErrors = graphQLResultHasError(action.result);
newState[action.queryId] = __assign$7({}, previousState[action.queryId], { networkError: null, graphQLErrors: resultHasGraphQLErrors ? action.result.errors : [], previousVariables: null, networkStatus: exports.NetworkStatus.ready });
return newState;
}
else if (isQueryErrorAction(action)) {
if (!previousState[action.queryId]) {
return previousState;
}
if (action.requestId < previousState[action.queryId].lastRequestId) {
return previousState;
}
var newState = __assign$7({}, previousState);
newState[action.queryId] = __assign$7({}, previousState[action.queryId], { networkError: action.error, networkStatus: exports.NetworkStatus.error });
return newState;
}
else if (isQueryResultClientAction(action)) {
if (!previousState[action.queryId]) {
return previousState;
}
var newState = __assign$7({}, previousState);
newState[action.queryId] = __assign$7({}, previousState[action.queryId], { networkError: null, previousVariables: null, networkStatus: action.complete ? exports.NetworkStatus.ready : exports.NetworkStatus.loading });
return newState;
}
else if (isQueryStopAction(action)) {
var newState = __assign$7({}, previousState);
delete newState[action.queryId];
return newState;
}
else if (isStoreResetAction(action)) {
return resetQueryState(previousState, action);
}
return previousState;
}
function resetQueryState(state, action) {
var observableQueryIds = action.observableQueryIds;
var newQueries = Object.keys(state).filter(function (queryId) {
return (observableQueryIds.indexOf(queryId) > -1);
}).reduce(function (res, key) {
res[key] = __assign$7({}, state[key], { networkStatus: exports.NetworkStatus.loading });
return res;
}, {});
return newQueries;
}
var __assign$8 = (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;
};
function mutations(previousState, action) {
if (previousState === void 0) { previousState = {}; }
if (isMutationInitAction(action)) {
var newState = __assign$8({}, previousState);
newState[action.mutationId] = {
mutationString: action.mutationString,
variables: action.variables,
loading: true,
error: null,
};
return newState;
}
else if (isMutationResultAction(action)) {
var newState = __assign$8({}, previousState);
newState[action.mutationId] = __assign$8({}, previousState[action.mutationId], { loading: false, error: null });
return newState;
}
else if (isMutationErrorAction(action)) {
var newState = __assign$8({}, previousState);
newState[action.mutationId] = __assign$8({}, previousState[action.mutationId], { loading: false, error: action.error });
}
else if (isStoreResetAction(action)) {
return {};
}
return previousState;
}
var __assign$9 = (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 optimisticDefaultState = [];
function getDataWithOptimisticResults(store) {
if (store.optimistic.length === 0) {
return store.data;
}
var patches = store.optimistic.map(function (opt) { return opt.data; });
return assign.apply(void 0, [{}, store.data].concat(patches));
}
function optimistic(previousState, action, store, config) {
if (previousSt