Last active
August 11, 2017 19:46
-
-
Save jimthedev/a99d11fc37753d183423d2507d6f81e1 to your computer and use it in GitHub Desktop.
apollo-client 1.8 v 1.9
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function (global, factory) { | |
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('whatwg-fetch'), require('graphql/language/printer'), require('redux'), require('graphql-anywhere'), require('symbol-observable'), require('apollo-link-core')) : | |
typeof define === 'function' && define.amd ? define(['exports', 'whatwg-fetch', 'graphql/language/printer', 'redux', 'graphql-anywhere', 'symbol-observable', 'apollo-link-core'], factory) : | |
(factory((global.apollo = {}),null,global.graphql_language_printer,global.Redux,global.graphqlAnywhere,global.$$observable,global.apolloLinkCore)); | |
}(this, (function (exports,whatwgFetch,graphql_language_printer,redux,graphqlAnywhere,$$observable,apolloLinkCore) { 'use strict'; | |
graphqlAnywhere = graphqlAnywhere && graphqlAnywhere.hasOwnProperty('default') ? graphqlAnywhere['default'] : graphqlAnywhere; | |
$$observable = $$observable && $$observable.hasOwnProperty('default') ? $$observable['default'] : $$observable; | |
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) { | |
var directivesObj = null; | |
if (field.directives) { | |
directivesObj = {}; | |
field.directives.forEach(function (directive) { | |
directivesObj[directive.name.value] = {}; | |
if (directive.arguments) { | |
directive.arguments.forEach(function (_a) { | |
var name = _a.name, value = _a.value; | |
return valueToObjectRepresentation(directivesObj[directive.name.value], name, value, variables); | |
}); | |
} | |
}); | |
} | |
var argObj = null; | |
if (field.arguments && field.arguments.length) { | |
argObj = {}; | |
field.arguments.forEach(function (_a) { | |
var name = _a.name, value = _a.value; | |
return valueToObjectRepresentation(argObj, name, value, variables); | |
}); | |
} | |
return getStoreKeyName(field.name.value, argObj, directivesObj); | |
} | |
function getStoreKeyName(fieldName, args, directives) { | |
if (directives && | |
directives['connection'] && | |
directives['connection']['key']) { | |
if (directives['connection']['filter'] && | |
directives['connection']['filter'].length > 0) { | |
var filterKeys = directives['connection']['filter'] | |
? directives['connection']['filter'] | |
: []; | |
filterKeys.sort(); | |
var queryArgs_1 = args; | |
var filteredArgs_1 = {}; | |
filterKeys.forEach(function (key) { | |
filteredArgs_1[key] = queryArgs_1[key]; | |
}); | |
return directives['connection']['key'] + "(" + JSON.stringify(filteredArgs_1) + ")"; | |
} | |
else { | |
return directives['connection']['key']; | |
} | |
} | |
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 assign(target) { | |
var sources = []; | |
for (var _i = 1; _i < arguments.length; _i++) { | |
sources[_i - 1] = arguments[_i]; | |
} | |
sources.forEach(function (source) { | |
if (typeof source === 'undefined' || source === null) { | |
return; | |
} | |
Object.keys(source).forEach(function (key) { | |
target[key] = source[key]; | |
}); | |
}); | |
return target; | |
} | |
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; | |
}; | |
function getMutationDefinition(doc) { | |
checkDocument(doc); | |
var mutationDef = null; | |
doc.definitions.forEach(function (definition) { | |
if (definition.kind === 'OperationDefinition' && | |
definition.operation === 'mutation') { | |
mutationDef = definition; | |
} | |
}); | |
if (!mutationDef) { | |
throw new Error('Must contain a mutation definition.'); | |
} | |
return mutationDef; | |
} | |
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 = null; | |
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 getFragmentQueryDocument(document, fragmentName) { | |
var actualFragmentName = fragmentName; | |
var fragments = []; | |
document.definitions.forEach(function (definition) { | |
if (definition.kind === 'OperationDefinition') { | |
throw new Error("Found a " + definition.operation + " operation" + (definition.name | |
? " named '" + definition.name.value + "'" | |
: '') + ". " + | |
'No operations are allowed when using a fragment as a query. Only fragments are allowed.'); | |
} | |
if (definition.kind === 'FragmentDefinition') { | |
fragments.push(definition); | |
} | |
}); | |
if (typeof actualFragmentName === 'undefined') { | |
if (fragments.length !== 1) { | |
throw new Error("Found " + fragments.length + " fragments. `fragmentName` must be provided when there is not exactly 1 fragment."); | |
} | |
actualFragmentName = fragments[0].name.value; | |
} | |
var query = __assign$1({}, document, { definitions: [ | |
{ | |
kind: 'OperationDefinition', | |
operation: 'query', | |
selectionSet: { | |
kind: 'SelectionSet', | |
selections: [ | |
{ | |
kind: 'FragmentSpread', | |
name: { | |
kind: 'Name', | |
value: actualFragmentName, | |
}, | |
}, | |
], | |
}, | |
} | |
].concat(document.definitions) }); | |
return query; | |
} | |
function getDefaultValues(definition) { | |
if (definition.variableDefinitions && definition.variableDefinitions.length) { | |
var defaultValues = definition.variableDefinitions | |
.filter(function (_a) { | |
var defaultValue = _a.defaultValue; | |
return defaultValue; | |
}) | |
.map(function (_a) { | |
var variable = _a.variable, defaultValue = _a.defaultValue; | |
var defaultValueObj = {}; | |
valueToObjectRepresentation(defaultValueObj, variable.name, defaultValue); | |
return defaultValueObj; | |
}); | |
return assign.apply(void 0, [{}].concat(defaultValues)); | |
} | |
return {}; | |
} | |
function cloneDeep(value) { | |
if (Array.isArray(value)) { | |
return value.map(function (item) { return cloneDeep(item); }); | |
} | |
if (value !== null && typeof value === 'object') { | |
var nextValue = {}; | |
for (var key in value) { | |
if (value.hasOwnProperty(key)) { | |
nextValue[key] = cloneDeep(value[key]); | |
} | |
} | |
return nextValue; | |
} | |
return value; | |
} | |
var TYPENAME_FIELD = { | |
kind: 'Field', | |
name: { | |
kind: 'Name', | |
value: '__typename', | |
}, | |
}; | |
function addTypenameToSelectionSet(selectionSet, isRoot) { | |
if (isRoot === void 0) { isRoot = false; } | |
if (selectionSet.selections) { | |
if (!isRoot) { | |
var alreadyHasThisField = selectionSet.selections.some(function (selection) { | |
return (selection.kind === 'Field' && | |
selection.name.value === '__typename'); | |
}); | |
if (!alreadyHasThisField) { | |
selectionSet.selections.push(TYPENAME_FIELD); | |
} | |
} | |
selectionSet.selections.forEach(function (selection) { | |
if (selection.kind === 'Field') { | |
if (selection.name.value.lastIndexOf('__', 0) !== 0 && | |
selection.selectionSet) { | |
addTypenameToSelectionSet(selection.selectionSet); | |
} | |
} | |
else if (selection.kind === 'InlineFragment') { | |
if (selection.selectionSet) { | |
addTypenameToSelectionSet(selection.selectionSet); | |
} | |
} | |
}); | |
} | |
} | |
function removeConnectionDirectiveFromSelectionSet(selectionSet) { | |
if (selectionSet.selections) { | |
selectionSet.selections.forEach(function (selection) { | |
if (selection.kind === 'Field' && | |
selection && | |
selection.directives) { | |
selection.directives = selection.directives.filter(function (directive) { | |
var willRemove = directive.name.value === 'connection'; | |
if (willRemove) { | |
if (!directive.arguments || | |
!directive.arguments.some(function (arg) { return arg.name.value === 'key'; })) { | |
console.warn('Removing an @connection directive even though it does not have a key. ' + | |
'You may want to use the key parameter to specify a store key.'); | |
} | |
} | |
return !willRemove; | |
}); | |
} | |
}); | |
selectionSet.selections.forEach(function (selection) { | |
if (selection.kind === 'Field') { | |
if (selection.selectionSet) { | |
removeConnectionDirectiveFromSelectionSet(selection.selectionSet); | |
} | |
} | |
else if (selection.kind === 'InlineFragment') { | |
if (selection.selectionSet) { | |
removeConnectionDirectiveFromSelectionSet(selection.selectionSet); | |
} | |
} | |
}); | |
} | |
} | |
function addTypenameToDocument(doc) { | |
checkDocument(doc); | |
var docClone = cloneDeep(doc); | |
docClone.definitions.forEach(function (definition) { | |
var isRoot = definition.kind === 'OperationDefinition'; | |
addTypenameToSelectionSet(definition.selectionSet, isRoot); | |
}); | |
return docClone; | |
} | |
function removeConnectionDirectiveFromDocument(doc) { | |
checkDocument(doc); | |
var docClone = cloneDeep(doc); | |
docClone.definitions.forEach(function (definition) { | |
removeConnectionDirectiveFromSelectionSet(definition.selectionSet); | |
}); | |
return docClone; | |
} | |
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 __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: graphql_language_printer.print(request.query) }); | |
} | |
var BaseNetworkInterface = (function () { | |
function BaseNetworkInterface(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 = []; | |
} | |
BaseNetworkInterface.prototype.query = function (request) { | |
return new Promise(function (resolve, reject) { | |
reject(new Error('BaseNetworkInterface should not be used directly')); | |
}); | |
}; | |
return BaseNetworkInterface; | |
}()); | |
var HTTPFetchNetworkInterface = (function (_super) { | |
__extends(HTTPFetchNetworkInterface, _super); | |
function HTTPFetchNetworkInterface() { | |
return _super !== null && _super.apply(this, arguments) || this; | |
} | |
HTTPFetchNetworkInterface.prototype.applyMiddlewares = function (requestAndOptions) { | |
var _this = this; | |
return new Promise(function (resolve, reject) { | |
var request = requestAndOptions.request, options = requestAndOptions.options; | |
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 responseObject = { response: response, options: options }; | |
var queue = function (funcs, scope) { | |
var next = function () { | |
if (funcs.length > 0) { | |
var f = funcs.shift(); | |
if (f) { | |
f.applyAfterware.apply(scope, [responseObject, next]); | |
} | |
} | |
else { | |
resolve(responseObject); | |
} | |
}; | |
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) { | |
if (rao.request.query) { | |
rao.request.query = removeConnectionDirectiveFromDocument(rao.request.query); | |
} | |
return rao; | |
}) | |
.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; | |
return httpResponse.json().catch(function (error) { | |
var httpError = new Error("Network request failed with status " + response.status + " - \"" + response.statusText + "\""); | |
httpError.response = httpResponse; | |
httpError.parseError = error; | |
throw httpError; | |
}); | |
}) | |
.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; | |
}(BaseNetworkInterface)); | |
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.opts; | |
uri = uriOrInterfaceOpts; | |
} | |
else { | |
opts = uriOrInterfaceOpts.opts; | |
uri = uriOrInterfaceOpts.uri; | |
} | |
return new HTTPFetchNetworkInterface(uri, opts); | |
} | |
var QueryBatcher = (function () { | |
function QueryBatcher(_a) { | |
var batchInterval = _a.batchInterval, _b = _a.batchMax, batchMax = _b === void 0 ? 0 : _b, batchFetchFunction = _a.batchFetchFunction; | |
this.queuedRequests = []; | |
this.queuedRequests = []; | |
this.batchInterval = batchInterval; | |
this.batchMax = batchMax; | |
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; | |
}); | |
if (this.queuedRequests.length === 1) { | |
this.scheduleQueueConsumption(); | |
} | |
if (this.queuedRequests.length === this.batchMax) { | |
this.consumeQueue(); | |
} | |
return fetchRequest.promise; | |
}; | |
QueryBatcher.prototype.consumeQueue = function () { | |
var requests = this.queuedRequests.map(function (queuedRequest) { return queuedRequest.request; }); | |
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.scheduleQueueConsumption = function () { | |
var _this = this; | |
setTimeout(function () { | |
if (_this.queuedRequests.length) { | |
_this.consumeQueue(); | |
} | |
}, this.batchInterval); | |
}; | |
return QueryBatcher; | |
}()); | |
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$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 HTTPBatchedNetworkInterface = (function (_super) { | |
__extends$1(HTTPBatchedNetworkInterface, _super); | |
function HTTPBatchedNetworkInterface(_a) { | |
var uri = _a.uri, _b = _a.batchInterval, batchInterval = _b === void 0 ? 10 : _b, _c = _a.batchMax, batchMax = _c === void 0 ? 0 : _c, fetchOpts = _a.fetchOpts; | |
var _this = _super.call(this, uri, fetchOpts) || this; | |
if (typeof batchInterval !== 'number') { | |
throw new Error("batchInterval must be a number, got " + batchInterval); | |
} | |
if (typeof batchMax !== 'number') { | |
throw new Error("batchMax must be a number, got " + batchMax); | |
} | |
_this.batcher = new QueryBatcher({ | |
batchInterval: batchInterval, | |
batchMax: batchMax, | |
batchFetchFunction: _this.batchQuery.bind(_this), | |
}); | |
return _this; | |
} | |
HTTPBatchedNetworkInterface.prototype.query = function (request) { | |
return this.batcher.enqueueRequest(request); | |
}; | |
HTTPBatchedNetworkInterface.prototype.batchQuery = function (requests) { | |
var _this = this; | |
var options = __assign$2({}, this._opts); | |
var middlewarePromise = this.applyBatchMiddlewares({ | |
requests: requests, | |
options: options, | |
}); | |
return new Promise(function (resolve, reject) { | |
middlewarePromise | |
.then(function (batchRequestAndOptions) { | |
batchRequestAndOptions.requests.forEach(function (r) { | |
if (r.query) | |
r.query = removeConnectionDirectiveFromDocument(r.query); | |
}); | |
return _this.batchedFetchFromRemoteEndpoint(batchRequestAndOptions) | |
.then(function (result) { | |
var httpResponse = result; | |
if (!httpResponse.ok) { | |
return _this.applyBatchAfterwares({ | |
responses: [httpResponse], | |
options: batchRequestAndOptions.options, | |
}).then(function () { | |
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'); | |
} | |
_this.applyBatchAfterwares({ | |
responses: responses, | |
options: batchRequestAndOptions.options, | |
}) | |
.then(function (responseAndOptions) { | |
resolve(responseAndOptions.responses); | |
}) | |
.catch(function (error) { | |
reject(error); | |
}); | |
}); | |
}) | |
.catch(function (error) { | |
reject(error); | |
}); | |
}); | |
}; | |
HTTPBatchedNetworkInterface.prototype.applyBatchMiddlewares = function (_a) { | |
var _this = this; | |
var requests = _a.requests, 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.applyBatchMiddleware.apply(scope, [ | |
{ requests: requests, options: options }, | |
next, | |
]); | |
} | |
} | |
else { | |
resolve({ | |
requests: requests, | |
options: options, | |
}); | |
} | |
}; | |
next(); | |
}; | |
queue(_this._middlewares.slice(), _this); | |
}); | |
}; | |
HTTPBatchedNetworkInterface.prototype.applyBatchAfterwares = function (_a) { | |
var _this = this; | |
var responses = _a.responses, options = _a.options; | |
return new Promise(function (resolve, reject) { | |
var responseObject = { responses: responses, options: options }; | |
var queue = function (funcs, scope) { | |
var next = function () { | |
if (funcs.length > 0) { | |
var f = funcs.shift(); | |
if (f) { | |
f.applyBatchAfterware.apply(scope, [responseObject, next]); | |
} | |
} | |
else { | |
resolve(responseObject); | |
} | |
}; | |
next(); | |
}; | |
queue(_this._afterwares.slice(), _this); | |
}); | |
}; | |
HTTPBatchedNetworkInterface.prototype.use = function (middlewares) { | |
var _this = this; | |
middlewares.map(function (middleware) { | |
if (typeof middleware.applyBatchMiddleware === 'function') { | |
_this._middlewares.push(middleware); | |
} | |
else { | |
throw new Error('Batch middleware must implement the applyBatchMiddleware function'); | |
} | |
}); | |
return this; | |
}; | |
HTTPBatchedNetworkInterface.prototype.useAfter = function (afterwares) { | |
var _this = this; | |
afterwares.map(function (afterware) { | |
if (typeof afterware.applyBatchAfterware === 'function') { | |
_this._afterwares.push(afterware); | |
} | |
else { | |
throw new Error('Batch afterware must implement the applyBatchAfterware function'); | |
} | |
}); | |
return this; | |
}; | |
HTTPBatchedNetworkInterface.prototype.batchedFetchFromRemoteEndpoint = function (batchRequestAndOptions) { | |
var options = {}; | |
assign(options, batchRequestAndOptions.options); | |
var printedRequests = batchRequestAndOptions.requests.map(function (request) { | |
return printRequest(request); | |
}); | |
return fetch(this._uri, __assign$2({}, this._opts, { body: JSON.stringify(printedRequests), method: 'POST' }, options, { headers: __assign$2({ Accept: '*/*', 'Content-Type': 'application/json' }, options.headers) })); | |
}; | |
return HTTPBatchedNetworkInterface; | |
}(BaseNetworkInterface)); | |
function createBatchingNetworkInterface(options) { | |
if (!options) { | |
throw new Error('You must pass an options argument to createNetworkInterface.'); | |
} | |
return new HTTPBatchedNetworkInterface({ | |
uri: options.uri, | |
batchInterval: options.batchInterval, | |
batchMax: options.batchMax, | |
fetchOpts: options.opts || {}, | |
}); | |
} | |
function isQueryResultAction(action) { | |
return action.type === 'APOLLO_QUERY_RESULT'; | |
} | |
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 isWriteAction(action) { | |
return action.type === 'APOLLO_WRITE'; | |
} | |
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; | |
} | |
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 __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$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; | |
}; | |
var WriteError = (function (_super) { | |
__extends$2(WriteError, _super); | |
function WriteError() { | |
var _this = _super !== null && _super.apply(this, arguments) || this; | |
_this.type = 'WriteError'; | |
return _this; | |
} | |
return WriteError; | |
}(Error)); | |
function enhanceErrorWithDocument(error, document) { | |
var enhancedError = new WriteError("Error writing result to store for query " + (document.loc && | |
document.loc.source && | |
document.loc.source.body)); | |
enhancedError.message += '/n' + error.message; | |
enhancedError.stack = error.stack; | |
return enhancedError; | |
} | |
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, fragmentMatcherFunction = _a.fragmentMatcherFunction; | |
var queryDefinition = getQueryDefinition(query); | |
variables = assign({}, getDefaultValues(queryDefinition), variables); | |
try { | |
return writeSelectionSetToStore({ | |
dataId: 'ROOT_QUERY', | |
result: result, | |
selectionSet: queryDefinition.selectionSet, | |
context: { | |
store: store, | |
processedData: {}, | |
variables: variables, | |
dataIdFromObject: dataIdFromObject, | |
fragmentMap: fragmentMap, | |
fragmentMatcherFunction: fragmentMatcherFunction, | |
}, | |
}); | |
} | |
catch (e) { | |
throw enhanceErrorWithDocument(e, query); | |
} | |
} | |
function writeResultToStore(_a) { | |
var dataId = _a.dataId, result = _a.result, document = _a.document, _b = _a.store, store = _b === void 0 ? {} : _b, variables = _a.variables, dataIdFromObject = _a.dataIdFromObject, fragmentMatcherFunction = _a.fragmentMatcherFunction; | |
var operationDefinition = getOperationDefinition(document); | |
var selectionSet = operationDefinition.selectionSet; | |
var fragmentMap = createFragmentMap(getFragmentDefinitions(document)); | |
variables = assign({}, getDefaultValues(operationDefinition), variables); | |
try { | |
return writeSelectionSetToStore({ | |
result: result, | |
dataId: dataId, | |
selectionSet: selectionSet, | |
context: { | |
store: store, | |
processedData: {}, | |
variables: variables, | |
dataIdFromObject: dataIdFromObject, | |
fragmentMap: fragmentMap, | |
fragmentMatcherFunction: fragmentMatcherFunction, | |
}, | |
}); | |
} | |
catch (e) { | |
throw enhanceErrorWithDocument(e, document); | |
} | |
} | |
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 (included) { | |
if (typeof value !== 'undefined') { | |
writeFieldToStore({ | |
dataId: dataId, | |
value: value, | |
field: selection, | |
context: context, | |
}); | |
} | |
else { | |
if (context.fragmentMatcherFunction) { | |
if (!isProduction()) { | |
console.warn("Missing field " + resultFieldKey + " in " + JSON.stringify(result, null, 2).substring(0, 100)); | |
} | |
} | |
} | |
} | |
} | |
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 + "."); | |
} | |
} | |
var matches = true; | |
if (context.fragmentMatcherFunction && fragment.typeCondition) { | |
var idValue = { type: 'id', id: 'self', generated: false }; | |
var fakeContext = { | |
store: { self: result }, | |
returnPartialData: false, | |
hasMissingField: false, | |
customResolvers: {}, | |
}; | |
matches = context.fragmentMatcherFunction(idValue, fragment.typeCondition.name.value, fakeContext); | |
if (fakeContext.returnPartialData) { | |
console.error('WARNING: heuristic fragment matching going on!'); | |
} | |
} | |
if (included && matches) { | |
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$5({}, generated, real); | |
}); | |
} | |
function isDataProcessed(dataId, field, processedData) { | |
if (!processedData) { | |
return false; | |
} | |
if (processedData[dataId]) { | |
if (processedData[dataId].indexOf(field) >= 0) { | |
return true; | |
} | |
else { | |
processedData[dataId].push(field); | |
} | |
} | |
else { | |
processedData[dataId] = [field]; | |
} | |
return false; | |
} | |
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; | |
} | |
} | |
if (!isDataProcessed(valueDataId, field, context.processedData)) { | |
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$5({}, 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; | |
} | |
} | |
if (!isDataProcessed(itemDataId, selectionSet, context.processedData)) { | |
writeSelectionSetToStore({ | |
dataId: itemDataId, | |
result: item, | |
selectionSet: selectionSet, | |
context: context, | |
}); | |
} | |
var idStoreValue = { | |
type: 'id', | |
id: itemDataId, | |
generated: generated, | |
}; | |
return idStoreValue; | |
}); | |
} | |
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; | |
}; | |
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 (previousState === void 0) { previousState = optimisticDefaultState; } | |
if (isMutationInitAction(action) && action.optimisticResponse) { | |
var optimisticResponse = void 0; | |
if (typeof action.optimisticResponse === 'function') { | |
optimisticResponse = action.optimisticResponse(action.variables); | |
} | |
else { | |
optimisticResponse = action.optimisticResponse; | |
} | |
var fakeMutationResultAction = { | |
type: 'APOLLO_MUTATION_RESULT', | |
result: { data: optimisticResponse }, | |
document: action.mutation, | |
operationName: action.operationName, | |
variables: action.variables, | |
mutationId: action.mutationId, | |
extraReducers: action.extraReducers, | |
updateQueries: action.updateQueries, | |
update: action.update, | |
}; | |
var optimisticData = getDataWithOptimisticResults(__assign$7({}, store, { optimistic: previousState })); | |
var patch = getOptimisticDataPatch(optimisticData, fakeMutationResultAction, store.queries, store.mutations, config); | |
var optimisticState = { | |
action: fakeMutationResultAction, | |
data: patch, | |
mutationId: action.mutationId, | |
}; | |
var newState = previousState.concat([optimisticState]); | |
return newState; | |
} | |
else if ((isMutationErrorAction(action) || isMutationResultAction(action)) && | |
previousState.some(function (change) { return change.mutationId === action.mutationId; })) { | |
return rollbackOptimisticData(function (change) { return change.mutationId === action.mutationId; }, previousState, store, config); | |
} | |
return previousState; | |
} | |
function getOptimisticDataPatch(previousData, optimisticAction, queries, mutations, config) { | |
var optimisticData = data(previousData, optimisticAction, config); | |
var patch = {}; | |
Object.keys(optimisticData).forEach(function (key) { | |
if (optimisticData[key] !== previousData[key]) { | |
patch[key] = optimisticData[key]; | |
} | |
}); | |
return patch; | |
} | |
function rollbackOptimisticData(filterFn, previousState, store, config) { | |
if (previousState === void 0) { previousState = optimisticDefaultState; } | |
var optimisticData = assign({}, store.data); | |
var newState = previousState | |
.filter(function (item) { return !filterFn(item); }) | |
.map(function (change) { | |
var patch = getOptimisticDataPatch(optimisticData, change.action, store.queries, store.mutations, config); | |
assign(optimisticData, patch); | |
return __assign$7({}, change, { data: patch }); | |
}); | |
return newState; | |
} | |
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; | |
} | |
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; | |
}; | |
var ID_KEY = typeof Symbol !== 'undefined' ? Symbol('id') : '@@id'; | |
function readQueryFromStore(options) { | |
var optsPatch = { returnPartialData: false }; | |
return diffQueryAgainstStore(__assign$8({}, options, optsPatch)).result; | |
} | |
var readStoreResolver = function (fieldName, idValue, args, context, _a) { | |
var resultKey = _a.resultKey, directives = _a.directives; | |
assertIdValue(idValue); | |
var objId = idValue.id; | |
var obj = context.store[objId]; | |
var storeKeyName = getStoreKeyName(fieldName, args, directives); | |
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) + "."); | |
} | |
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, previousResult = _a.previousResult, _b = _a.returnPartialData, returnPartialData = _b === void 0 ? true : _b, _c = _a.rootId, rootId = _c === void 0 ? 'ROOT_QUERY' : _c, fragmentMatcherFunction = _a.fragmentMatcherFunction, config = _a.config; | |
var queryDefinition = getQueryDefinition(query); | |
variables = assign({}, getDefaultValues(queryDefinition), variables); | |
var context = { | |
store: store, | |
returnPartialData: returnPartialData, | |
customResolvers: (config && config.customResolvers) || {}, | |
hasMissingField: false, | |
}; | |
var rootIdValue = { | |
type: 'id', | |
id: rootId, | |
previousResult: previousResult, | |
}; | |
var result = graphqlAnywhere(readStoreResolver, query, rootIdValue, context, variables, { | |
fragmentMatcher: fragmentMatcherFunction, | |
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$8({}, value, { previousResult: previousResult }); | |
} | |
else if (Array.isArray(value)) { | |
var idToPreviousResult_1 = {}; | |
if (Array.isArray(previousResult)) { | |
previousResult.forEach(function (item) { | |
if (item && 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); | |
} | |
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 ReduxDataProxy = (function () { | |
function ReduxDataProxy(store, reduxRootSelector, fragmentMatcher, reducerConfig) { | |
this.store = store; | |
this.reduxRootSelector = reduxRootSelector; | |
this.reducerConfig = reducerConfig; | |
this.fragmentMatcher = fragmentMatcher; | |
} | |
ReduxDataProxy.prototype.readQuery = function (_a) { | |
var query = _a.query, variables = _a.variables; | |
if (this.reducerConfig.addTypename) { | |
query = addTypenameToDocument(query); | |
} | |
return readQueryFromStore({ | |
rootId: 'ROOT_QUERY', | |
store: getDataWithOptimisticResults(this.reduxRootSelector(this.store.getState())), | |
query: query, | |
variables: variables, | |
fragmentMatcherFunction: this.fragmentMatcher.match, | |
config: this.reducerConfig, | |
}); | |
}; | |
ReduxDataProxy.prototype.readFragment = function (_a) { | |
var id = _a.id, fragment = _a.fragment, fragmentName = _a.fragmentName, variables = _a.variables; | |
var query = getFragmentQueryDocument(fragment, fragmentName); | |
var data = getDataWithOptimisticResults(this.reduxRootSelector(this.store.getState())); | |
if (typeof data[id] === 'undefined') { | |
return null; | |
} | |
if (this.reducerConfig.addTypename) { | |
query = addTypenameToDocument(query); | |
} | |
return readQueryFromStore({ | |
rootId: id, | |
store: data, | |
query: query, | |
variables: variables, | |
fragmentMatcherFunction: this.fragmentMatcher.match, | |
config: this.reducerConfig, | |
}); | |
}; | |
ReduxDataProxy.prototype.writeQuery = function (_a) { | |
var data = _a.data, query = _a.query, variables = _a.variables; | |
if (this.reducerConfig.addTypename) { | |
query = addTypenameToDocument(query); | |
} | |
this.store.dispatch({ | |
type: 'APOLLO_WRITE', | |
writes: [ | |
{ | |
rootId: 'ROOT_QUERY', | |
result: data, | |
document: query, | |
operationName: getOperationName(query), | |
variables: variables || {}, | |
}, | |
], | |
}); | |
}; | |
ReduxDataProxy.prototype.writeFragment = function (_a) { | |
var data = _a.data, id = _a.id, fragment = _a.fragment, fragmentName = _a.fragmentName, variables = _a.variables; | |
var document = getFragmentQueryDocument(fragment, fragmentName); | |
if (this.reducerConfig.addTypename) { | |
document = addTypenameToDocument(document); | |
} | |
this.store.dispatch({ | |
type: 'APOLLO_WRITE', | |
writes: [ | |
{ | |
rootId: id, | |
result: data, | |
document: document, | |
operationName: getOperationName(document), | |
variables: variables || {}, | |
}, | |
], | |
}); | |
}; | |
return ReduxDataProxy; | |
}()); | |
var TransactionDataProxy = (function () { | |
function TransactionDataProxy(data, reducerConfig) { | |
this.data = __assign$6({}, data); | |
this.reducerConfig = reducerConfig; | |
this.writes = []; | |
this.isFinished = false; | |
} | |
TransactionDataProxy.prototype.finish = function () { | |
this.assertNotFinished(); | |
var writes = this.writes; | |
this.writes = []; | |
this.isFinished = true; | |
return writes; | |
}; | |
TransactionDataProxy.prototype.readQuery = function (_a) { | |
var query = _a.query, variables = _a.variables; | |
this.assertNotFinished(); | |
if (this.reducerConfig.addTypename) { | |
query = addTypenameToDocument(query); | |
} | |
return readQueryFromStore({ | |
rootId: 'ROOT_QUERY', | |
store: this.data, | |
query: query, | |
variables: variables, | |
config: this.reducerConfig, | |
fragmentMatcherFunction: this.reducerConfig.fragmentMatcher, | |
}); | |
}; | |
TransactionDataProxy.prototype.readFragment = function (_a) { | |
var id = _a.id, fragment = _a.fragment, fragmentName = _a.fragmentName, variables = _a.variables; | |
this.assertNotFinished(); | |
if (!fragment) { | |
throw new Error('fragment option is required. Please pass a GraphQL fragment to readFragment.'); | |
} | |
var data = this.data; | |
var query = getFragmentQueryDocument(fragment, fragmentName); | |
if (this.reducerConfig.addTypename) { | |
query = addTypenameToDocument(query); | |
} | |
if (typeof data[id] === 'undefined') { | |
return null; | |
} | |
return readQueryFromStore({ | |
rootId: id, | |
store: data, | |
query: query, | |
variables: variables, | |
config: this.reducerConfig, | |
fragmentMatcherFunction: this.reducerConfig.fragmentMatcher, | |
}); | |
}; | |
TransactionDataProxy.prototype.writeQuery = function (_a) { | |
var data = _a.data, query = _a.query, variables = _a.variables; | |
this.assertNotFinished(); | |
if (this.reducerConfig.addTypename) { | |
query = addTypenameToDocument(query); | |
} | |
this.applyWrite({ | |
rootId: 'ROOT_QUERY', | |
result: data, | |
document: query, | |
operationName: getOperationName(query), | |
variables: variables || {}, | |
}); | |
}; | |
TransactionDataProxy.prototype.writeFragment = function (_a) { | |
var data = _a.data, id = _a.id, fragment = _a.fragment, fragmentName = _a.fragmentName, variables = _a.variables; | |
this.assertNotFinished(); | |
if (!fragment) { | |
throw new Error('fragment option is required. Please pass a GraphQL fragment to writeFragment.'); | |
} | |
var query = getFragmentQueryDocument(fragment, fragmentName); | |
if (this.reducerConfig.addTypename) { | |
query = addTypenameToDocument(query); | |
} | |
this.applyWrite({ | |
rootId: id, | |
result: data, | |
document: query, | |
operationName: getOperationName(query), | |
variables: variables || {}, | |
}); | |
}; | |
TransactionDataProxy.prototype.assertNotFinished = function () { | |
if (this.isFinished) { | |
throw new Error('Cannot call transaction methods after the transaction has finished.'); | |
} | |
}; | |
TransactionDataProxy.prototype.applyWrite = function (write) { | |
writeResultToStore({ | |
result: write.result, | |
dataId: write.rootId, | |
document: write.document, | |
variables: write.variables, | |
store: this.data, | |
dataIdFromObject: this.reducerConfig.dataIdFromObject || (function () { return null; }), | |
fragmentMatcherFunction: this.reducerConfig.fragmentMatcher, | |
}); | |
this.writes.push(write); | |
}; | |
return TransactionDataProxy; | |
}()); | |
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; | |
}; | |
function replaceQueryResults(state, _a, config) { | |
var variables = _a.variables, document = _a.document, newResult = _a.newResult; | |
var clonedState = __assign$9({}, state); | |
return writeResultToStore({ | |
result: newResult, | |
dataId: 'ROOT_QUERY', | |
variables: variables, | |
document: document, | |
store: clonedState, | |
dataIdFromObject: config.dataIdFromObject, | |
fragmentMatcherFunction: config.fragmentMatcher, | |
}); | |
} | |
function tryFunctionOrLogError(f) { | |
try { | |
return f(); | |
} | |
catch (e) { | |
if (console.error) { | |
console.error(e); | |
} | |
} | |
} | |
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 data(previousState, action, config) { | |
if (previousState === void 0) { previousState = {}; } | |
var constAction = action; | |
if (isQueryResultAction(action)) { | |
if (action.fetchMoreForQueryId) { | |
return previousState; | |
} | |
if (!graphQLResultHasError(action.result)) { | |
var clonedState = __assign$4({}, previousState); | |
var newState_1 = writeResultToStore({ | |
result: action.result.data, | |
dataId: 'ROOT_QUERY', | |
document: action.document, | |
variables: action.variables, | |
store: clonedState, | |
dataIdFromObject: config.dataIdFromObject, | |
fragmentMatcherFunction: config.fragmentMatcher, | |
}); | |
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$4({}, previousState); | |
var newState_2 = writeResultToStore({ | |
result: action.result.data, | |
dataId: 'ROOT_SUBSCRIPTION', | |
document: action.document, | |
variables: action.variables, | |
store: clonedState, | |
dataIdFromObject: config.dataIdFromObject, | |
fragmentMatcherFunction: config.fragmentMatcher, | |
}); | |
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 clonedState = __assign$4({}, previousState); | |
var newState_3 = writeResultToStore({ | |
result: constAction.result.data, | |
dataId: 'ROOT_MUTATION', | |
document: constAction.document, | |
variables: constAction.variables, | |
store: clonedState, | |
dataIdFromObject: config.dataIdFromObject, | |
fragmentMatcherFunction: config.fragmentMatcher, | |
}); | |
var updateQueries_1 = constAction.updateQueries; | |
if (updateQueries_1) { | |
Object.keys(updateQueries_1) | |
.filter(function (id) { return updateQueries_1[id]; }) | |
.forEach(function (queryId) { | |
var _a = updateQueries_1[queryId], query = _a.query, reducer = _a.reducer; | |
var _b = diffQueryAgainstStore({ | |
store: previousState, | |
query: query.document, | |
variables: query.variables, | |
returnPartialData: true, | |
fragmentMatcherFunction: config.fragmentMatcher, | |
config: config, | |
}), currentQueryResult = _b.result, isMissing = _b.isMissing; | |
if (isMissing) { | |
return; | |
} | |
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, | |
fragmentMatcherFunction: config.fragmentMatcher, | |
}); | |
} | |
}); | |
} | |
if (constAction.update) { | |
var update_1 = constAction.update; | |
var proxy_1 = new TransactionDataProxy(newState_3, config); | |
tryFunctionOrLogError(function () { return update_1(proxy_1, constAction.result); }); | |
var writes = proxy_1.finish(); | |
newState_3 = data(newState_3, { type: 'APOLLO_WRITE', writes: writes }, config); | |
} | |
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 {}; | |
} | |
else if (isWriteAction(action)) { | |
return action.writes.reduce(function (currentState, write) { | |
return writeResultToStore({ | |
result: write.result, | |
dataId: write.rootId, | |
document: write.document, | |
variables: write.variables, | |
store: currentState, | |
dataIdFromObject: config.dataIdFromObject, | |
fragmentMatcherFunction: config.fragmentMatcher, | |
}); | |
}, __assign$4({}, previousState)); | |
} | |
return previousState; | |
} | |
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 crashReporter = function (store) { return function (next) { return function (action) { | |
try { | |
return next(action); | |
} | |
catch (err) { | |
console.error('Caught an exception!', err); | |
console.error(err.stack); | |
throw err; | |
} | |
}; }; }; | |
var createReducerError = function (error, action) { | |
var reducerError = { error: error }; | |
if (isQueryResultAction(action)) { | |
reducerError.queryId = action.queryId; | |
} | |
else if (isSubscriptionResultAction(action)) { | |
reducerError.subscriptionId = action.subscriptionId; | |
} | |
else if (isMutationResultAction(action)) { | |
reducerError.mutationId = action.mutationId; | |
} | |
return reducerError; | |
}; | |
function createApolloReducer(config) { | |
return function apolloReducer(state, action) { | |
if (state === void 0) { state = {}; } | |
try { | |
var newState = { | |
data: data(state.data, action, config), | |
optimistic: [], | |
reducerError: null, | |
}; | |
newState.optimistic = optimistic(state.optimistic, action, newState, config); | |
if (state.data === newState.data && | |
state.optimistic === newState.optimistic && | |
state.reducerError === newState.reducerError) { | |
return state; | |
} | |
return newState; | |
} | |
catch (reducerError) { | |
return __assign$3({}, state, { reducerError: createReducerError(reducerError, action) }); | |
} | |
}; | |
} | |
function createApolloStore(_a) { | |
var _b = _a === void 0 ? {} : _a, _c = _b.reduxRootKey, reduxRootKey = _c === void 0 ? 'apollo' : _c, initialState = _b.initialState, _d = _b.config, config = _d === void 0 ? {} : _d, _e = _b.reportCrashes, reportCrashes = _e === void 0 ? true : _e, logger = _b.logger; | |
var enhancers = []; | |
var middlewares = []; | |
if (reportCrashes) { | |
middlewares.push(crashReporter); | |
} | |
if (logger) { | |
middlewares.push(logger); | |
} | |
if (middlewares.length > 0) { | |
enhancers.push(redux.applyMiddleware.apply(void 0, middlewares)); | |
} | |
if (typeof window !== 'undefined') { | |
var anyWindow = window; | |
if (anyWindow.devToolsExtension) { | |
enhancers.push(anyWindow.devToolsExtension()); | |
} | |
} | |
var compose$$1 = redux.compose; | |
if (initialState && | |
initialState[reduxRootKey] && | |
initialState[reduxRootKey]['queries']) { | |
throw new Error('Apollo initial state may not contain queries, only data'); | |
} | |
if (initialState && | |
initialState[reduxRootKey] && | |
initialState[reduxRootKey]['mutations']) { | |
throw new Error('Apollo initial state may not contain mutations, only data'); | |
} | |
return redux.createStore(redux.combineReducers((_f = {}, _f[reduxRootKey] = createApolloReducer(config), _f)), initialState, compose$$1.apply(void 0, enhancers)); | |
var _f; | |
} | |
function isSubscription(subscription) { | |
return subscription.unsubscribe !== undefined; | |
} | |
var Observable = (function () { | |
function Observable(subscriberFunction) { | |
this.subscriberFunction = subscriberFunction; | |
} | |
Observable.prototype[$$observable] = function () { | |
return this; | |
}; | |
Observable.prototype.subscribe = function (observer) { | |
var subscriptionOrCleanupFunction = this.subscriberFunction(observer); | |
if (isSubscription(subscriptionOrCleanupFunction)) { | |
return subscriptionOrCleanupFunction; | |
} | |
else { | |
return { | |
unsubscribe: subscriptionOrCleanupFunction, | |
}; | |
} | |
}; | |
return Observable; | |
}()); | |
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 __()); | |
}; | |
})(); | |
function isApolloError(err) { | |
return err.hasOwnProperty('graphQLErrors'); | |
} | |
var generateErrorMessage = function (err) { | |
var message = ''; | |
if (Array.isArray(err.graphQLErrors) && err.graphQLErrors.length !== 0) { | |
err.graphQLErrors.forEach(function (graphQLError) { | |
var errorMessage = graphQLError | |
? graphQLError.message | |
: 'Error message not found.'; | |
message += "GraphQL error: " + errorMessage + "\n"; | |
}); | |
} | |
if (err.networkError) { | |
message += 'Network error: ' + err.networkError.message + '\n'; | |
} | |
message = message.replace(/\n$/, ''); | |
return message; | |
}; | |
var ApolloError = (function (_super) { | |
__extends$4(ApolloError, _super); | |
function ApolloError(_a) { | |
var graphQLErrors = _a.graphQLErrors, networkError = _a.networkError, errorMessage = _a.errorMessage, extraInfo = _a.extraInfo; | |
var _this = _super.call(this, errorMessage) || this; | |
_this.graphQLErrors = graphQLErrors || []; | |
_this.networkError = networkError || null; | |
if (!errorMessage) { | |
_this.message = generateErrorMessage(_this); | |
} | |
else { | |
_this.message = errorMessage; | |
} | |
_this.extraInfo = extraInfo; | |
return _this; | |
} | |
return ApolloError; | |
}(Error)); | |
var FetchType; | |
(function (FetchType) { | |
FetchType[FetchType["normal"] = 1] = "normal"; | |
FetchType[FetchType["refetch"] = 2] = "refetch"; | |
FetchType[FetchType["poll"] = 3] = "poll"; | |
})(FetchType || (FetchType = {})); | |
function deepFreeze(o) { | |
Object.freeze(o); | |
Object.getOwnPropertyNames(o).forEach(function (prop) { | |
if (o.hasOwnProperty(prop) && | |
o[prop] !== null && | |
(typeof o[prop] === 'object' || typeof o[prop] === 'function') && | |
!Object.isFrozen(o[prop])) { | |
deepFreeze(o[prop]); | |
} | |
}); | |
return o; | |
} | |
function maybeDeepFreeze(obj) { | |
if (isDevelopment() || isTest()) { | |
return deepFreeze(obj); | |
} | |
return obj; | |
} | |
(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 __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 __assign$10 = (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 ObservableQuery = (function (_super) { | |
__extends$3(ObservableQuery, _super); | |
function ObservableQuery(_a) { | |
var scheduler = _a.scheduler, options = _a.options, _b = _a.shouldSubscribe, shouldSubscribe = _b === void 0 ? true : _b; | |
var _this = this; | |
var queryManager = scheduler.queryManager; | |
var queryId = queryManager.generateQueryId(); | |
var subscriberFunction = function (observer) { | |
return _this.onSubscribe(observer); | |
}; | |
_this = _super.call(this, subscriberFunction) || this; | |
_this.isCurrentlyPolling = false; | |
_this.options = options; | |
_this.variables = _this.options.variables || {}; | |
_this.scheduler = scheduler; | |
_this.queryManager = queryManager; | |
_this.queryId = queryId; | |
_this.shouldSubscribe = shouldSubscribe; | |
_this.observers = []; | |
_this.subscriptionHandles = []; | |
return _this; | |
} | |
ObservableQuery.prototype.result = function () { | |
var that = this; | |
return new Promise(function (resolve, reject) { | |
var subscription = null; | |
var observer = { | |
next: function (result) { | |
resolve(result); | |
var selectedObservers = that.observers.filter(function (obs) { return obs !== observer; }); | |
if (selectedObservers.length === 0) { | |
that.queryManager.removeQuery(that.queryId); | |
} | |
setTimeout(function () { | |
subscription.unsubscribe(); | |
}, 0); | |
}, | |
error: function (error) { | |
reject(error); | |
}, | |
}; | |
subscription = that.subscribe(observer); | |
}); | |
}; | |
ObservableQuery.prototype.currentResult = function () { | |
var _a = this.queryManager.getCurrentQueryResult(this, true), data = _a.data, partial = _a.partial; | |
var queryStoreValue = this.queryManager.queryStore.get(this.queryId); | |
if (queryStoreValue && | |
((queryStoreValue.graphQLErrors && | |
queryStoreValue.graphQLErrors.length > 0) || | |
queryStoreValue.networkError)) { | |
var error = new ApolloError({ | |
graphQLErrors: queryStoreValue.graphQLErrors, | |
networkError: queryStoreValue.networkError, | |
}); | |
return { | |
data: {}, | |
loading: false, | |
networkStatus: queryStoreValue.networkStatus, | |
error: error, | |
}; | |
} | |
var queryLoading = !queryStoreValue || | |
queryStoreValue.networkStatus === exports.NetworkStatus.loading; | |
var loading = (this.options.fetchPolicy === 'network-only' && queryLoading) || | |
(partial && this.options.fetchPolicy !== 'cache-only'); | |
var networkStatus; | |
if (queryStoreValue) { | |
networkStatus = queryStoreValue.networkStatus; | |
} | |
else { | |
networkStatus = loading ? exports.NetworkStatus.loading : exports.NetworkStatus.ready; | |
} | |
var result = { | |
data: data, | |
loading: isNetworkRequestInFlight(networkStatus), | |
networkStatus: networkStatus, | |
}; | |
if (!partial) { | |
var stale = false; | |
this.lastResult = __assign$10({}, result, { stale: stale }); | |
} | |
return __assign$10({}, result, { partial: partial }); | |
}; | |
ObservableQuery.prototype.getLastResult = function () { | |
return this.lastResult; | |
}; | |
ObservableQuery.prototype.refetch = function (variables) { | |
this.variables = __assign$10({}, this.variables, variables); | |
if (this.options.fetchPolicy === 'cache-only') { | |
return Promise.reject(new Error('cache-only fetchPolicy option should not be used together with query refetch.')); | |
} | |
this.options.variables = __assign$10({}, this.options.variables, this.variables); | |
var combinedOptions = __assign$10({}, this.options, { fetchPolicy: 'network-only' }); | |
return this.queryManager | |
.fetchQuery(this.queryId, combinedOptions, FetchType.refetch) | |
.then(function (result) { return maybeDeepFreeze(result); }); | |
}; | |
ObservableQuery.prototype.fetchMore = function (fetchMoreOptions) { | |
var _this = this; | |
if (!fetchMoreOptions.updateQuery) { | |
throw new Error('updateQuery option is required. This function defines how to update the query data with the new results.'); | |
} | |
return Promise.resolve() | |
.then(function () { | |
var qid = _this.queryManager.generateQueryId(); | |
var combinedOptions = null; | |
if (fetchMoreOptions.query) { | |
combinedOptions = fetchMoreOptions; | |
} | |
else { | |
var variables = __assign$10({}, _this.variables, fetchMoreOptions.variables); | |
combinedOptions = __assign$10({}, _this.options, fetchMoreOptions, { variables: variables }); | |
} | |
combinedOptions = __assign$10({}, combinedOptions, { query: combinedOptions.query, fetchPolicy: 'network-only' }); | |
return _this.queryManager.fetchQuery(qid, combinedOptions, FetchType.normal, _this.queryId); | |
}) | |
.then(function (fetchMoreResult) { | |
var data = fetchMoreResult.data; | |
var reducer = fetchMoreOptions.updateQuery; | |
var mapFn = function (previousResult, _a) { | |
var variables = _a.variables; | |
var queryVariables = variables; | |
return reducer(previousResult, { | |
fetchMoreResult: data, | |
queryVariables: queryVariables, | |
}); | |
}; | |
_this.updateQuery(mapFn); | |
return fetchMoreResult; | |
}); | |
}; | |
ObservableQuery.prototype.subscribeToMore = function (options) { | |
var _this = this; | |
var observable = this.queryManager.startGraphQLSubscription({ | |
query: options.document, | |
variables: options.variables, | |
}); | |
var subscription = observable.subscribe({ | |
next: function (data) { | |
if (options.updateQuery) { | |
var reducer_1 = options.updateQuery; | |
var mapFn = function (previousResult, _a) { | |
var variables = _a.variables; | |
return reducer_1(previousResult, { | |
subscriptionData: { data: data }, | |
variables: variables, | |
}); | |
}; | |
_this.updateQuery(mapFn); | |
} | |
}, | |
error: function (err) { | |
if (options.onError) { | |
options.onError(err); | |
} | |
else { | |
console.error('Unhandled GraphQL subscription error', err); | |
} | |
}, | |
}); | |
this.subscriptionHandles.push(subscription); | |
return function () { | |
var i = _this.subscriptionHandles.indexOf(subscription); | |
if (i >= 0) { | |
_this.subscriptionHandles.splice(i, 1); | |
subscription.unsubscribe(); | |
} | |
}; | |
}; | |
ObservableQuery.prototype.setOptions = function (opts) { | |
var oldOptions = this.options; | |
this.options = __assign$10({}, this.options, opts); | |
if (opts.pollInterval) { | |
this.startPolling(opts.pollInterval); | |
} | |
else if (opts.pollInterval === 0) { | |
this.stopPolling(); | |
} | |
var tryFetch = (oldOptions.fetchPolicy !== 'network-only' && | |
opts.fetchPolicy === 'network-only') || | |
(oldOptions.fetchPolicy === 'cache-only' && | |
opts.fetchPolicy !== 'cache-only') || | |
(oldOptions.fetchPolicy === 'standby' && | |
opts.fetchPolicy !== 'standby') || | |
false; | |
return this.setVariables(this.options.variables, tryFetch, opts.fetchResults); | |
}; | |
ObservableQuery.prototype.setVariables = function (variables, tryFetch, fetchResults) { | |
if (tryFetch === void 0) { tryFetch = false; } | |
if (fetchResults === void 0) { fetchResults = true; } | |
var newVariables = __assign$10({}, this.variables, variables); | |
if (isEqual(newVariables, this.variables) && !tryFetch) { | |
if (this.observers.length === 0 || !fetchResults) { | |
return new Promise(function (resolve) { return resolve(); }); | |
} | |
return this.result(); | |
} | |
else { | |
this.variables = newVariables; | |
this.options.variables = newVariables; | |
if (this.observers.length === 0) { | |
return new Promise(function (resolve) { return resolve(); }); | |
} | |
return this.queryManager | |
.fetchQuery(this.queryId, __assign$10({}, this.options, { variables: this.variables })) | |
.then(function (result) { return maybeDeepFreeze(result); }); | |
} | |
}; | |
ObservableQuery.prototype.updateQuery = function (mapFn) { | |
var _a = this.queryManager.getQueryWithPreviousResult(this.queryId), previousResult = _a.previousResult, variables = _a.variables, document = _a.document; | |
var newResult = tryFunctionOrLogError(function () { | |
return mapFn(previousResult, { variables: variables }); | |
}); | |
if (newResult) { | |
this.queryManager.store.dispatch({ | |
type: 'APOLLO_UPDATE_QUERY_RESULT', | |
newResult: newResult, | |
variables: variables, | |
document: document, | |
operationName: getOperationName(document), | |
}); | |
} | |
}; | |
ObservableQuery.prototype.stopPolling = function () { | |
if (this.isCurrentlyPolling) { | |
this.scheduler.stopPollingQuery(this.queryId); | |
this.options.pollInterval = undefined; | |
this.isCurrentlyPolling = false; | |
} | |
}; | |
ObservableQuery.prototype.startPolling = function (pollInterval) { | |
if (this.options.fetchPolicy === 'cache-first' || | |
this.options.fetchPolicy === 'cache-only') { | |
throw new Error('Queries that specify the cache-first and cache-only fetchPolicies cannot also be polling queries.'); | |
} | |
if (this.isCurrentlyPolling) { | |
this.scheduler.stopPollingQuery(this.queryId); | |
this.isCurrentlyPolling = false; | |
} | |
this.options.pollInterval = pollInterval; | |
this.isCurrentlyPolling = true; | |
this.scheduler.startPollingQuery(this.options, this.queryId); | |
}; | |
ObservableQuery.prototype.onSubscribe = function (observer) { | |
var _this = this; | |
this.observers.push(observer); | |
if (observer.next && this.lastResult) { | |
observer.next(this.lastResult); | |
} | |
if (observer.error && this.lastError) { | |
observer.error(this.lastError); | |
} | |
if (this.observers.length === 1) { | |
this.setUpQuery(); | |
} | |
var retQuerySubscription = { | |
unsubscribe: function () { | |
if (!_this.observers.some(function (el) { return el === observer; })) { | |
return; | |
} | |
_this.observers = _this.observers.filter(function (obs) { return obs !== observer; }); | |
if (_this.observers.length === 0) { | |
_this.tearDownQuery(); | |
} | |
}, | |
}; | |
return retQuerySubscription; | |
}; | |
ObservableQuery.prototype.setUpQuery = function () { | |
var _this = this; | |
if (this.shouldSubscribe) { | |
this.queryManager.addObservableQuery(this.queryId, this); | |
} | |
if (!!this.options.pollInterval) { | |
if (this.options.fetchPolicy === 'cache-first' || | |
this.options.fetchPolicy === 'cache-only') { | |
throw new Error('Queries that specify the cache-first and cache-only fetchPolicies cannot also be polling queries.'); | |
} | |
this.isCurrentlyPolling = true; | |
this.scheduler.startPollingQuery(this.options, this.queryId); | |
} | |
var observer = { | |
next: function (result) { | |
_this.lastResult = result; | |
_this.observers.forEach(function (obs) { | |
if (obs.next) { | |
obs.next(result); | |
} | |
}); | |
}, | |
error: function (error) { | |
_this.observers.forEach(function (obs) { | |
if (obs.error) { | |
obs.error(error); | |
} | |
else { | |
console.error('Unhandled error', error.message, error.stack); | |
} | |
}); | |
_this.lastError = error; | |
}, | |
}; | |
this.queryManager.startQuery(this.queryId, this.options, this.queryManager.queryListenerForObserver(this.queryId, this.options, observer)); | |
}; | |
ObservableQuery.prototype.tearDownQuery = function () { | |
if (this.isCurrentlyPolling) { | |
this.scheduler.stopPollingQuery(this.queryId); | |
this.isCurrentlyPolling = false; | |
} | |
this.subscriptionHandles.forEach(function (sub) { return sub.unsubscribe(); }); | |
this.subscriptionHandles = []; | |
this.queryManager.stopQuery(this.queryId); | |
if (this.shouldSubscribe) { | |
this.queryManager.removeObservableQuery(this.queryId); | |
} | |
this.observers = []; | |
}; | |
return ObservableQuery; | |
}(Observable)); | |
var haveWarned$1 = Object.create({}); | |
function warnOnceInDevelopment(msg, type) { | |
if (type === void 0) { type = 'warn'; } | |
if (isProduction()) { | |
return; | |
} | |
if (!haveWarned$1[msg]) { | |
if (!isTest()) { | |
haveWarned$1[msg] = true; | |
} | |
switch (type) { | |
case 'error': | |
console.error(msg); | |
break; | |
default: | |
console.warn(msg); | |
} | |
} | |
} | |
var IntrospectionFragmentMatcher = (function () { | |
function IntrospectionFragmentMatcher(options) { | |
if (options && options.introspectionQueryResultData) { | |
this.possibleTypesMap = this.parseIntrospectionResult(options.introspectionQueryResultData); | |
this.isReady = true; | |
} | |
else { | |
this.isReady = false; | |
} | |
this.match = this.match.bind(this); | |
} | |
IntrospectionFragmentMatcher.prototype.match = function (idValue, typeCondition, context) { | |
if (!this.isReady) { | |
throw new Error('FragmentMatcher.match() was called before FragmentMatcher.init()'); | |
} | |
var obj = context.store[idValue.id]; | |
if (!obj) { | |
return false; | |
} | |
if (!obj.__typename) { | |
throw new Error("Cannot match fragment because __typename property is missing: " + JSON.stringify(obj)); | |
} | |
if (obj.__typename === typeCondition) { | |
return true; | |
} | |
var implementingTypes = this.possibleTypesMap[typeCondition]; | |
if (implementingTypes && implementingTypes.indexOf(obj.__typename) > -1) { | |
return true; | |
} | |
return false; | |
}; | |
IntrospectionFragmentMatcher.prototype.parseIntrospectionResult = function (introspectionResultData) { | |
var typeMap = {}; | |
introspectionResultData.__schema.types.forEach(function (type) { | |
if (type.kind === 'UNION' || type.kind === 'INTERFACE') { | |
typeMap[type.name] = type.possibleTypes.map(function (implementingType) { return implementingType.name; }); | |
} | |
}); | |
return typeMap; | |
}; | |
return IntrospectionFragmentMatcher; | |
}()); | |
var haveWarned = false; | |
var HeuristicFragmentMatcher = (function () { | |
function HeuristicFragmentMatcher() { | |
} | |
HeuristicFragmentMatcher.prototype.ensureReady = function () { | |
return Promise.resolve(); | |
}; | |
HeuristicFragmentMatcher.prototype.canBypassInit = function () { | |
return true; | |
}; | |
HeuristicFragmentMatcher.prototype.match = function (idValue, typeCondition, context) { | |
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 either don't have the addTypename:\n true option set in Apollo Client, or you are trying to write a fragment to the store without the __typename.\n Please turn on the addTypename option and include __typename when writing fragments so that Apollo Client\n can accurately match fragments."); | |
console.warn('Could not find __typename on Fragment ', typeCondition, obj); | |
console.warn("DEPRECATION WARNING: using fragments without __typename is unsupported behavior " + | |
"and will be removed in future versions of Apollo client. You should fix this and set addTypename to true now."); | |
if (!isTest()) { | |
haveWarned = true; | |
} | |
} | |
context.returnPartialData = true; | |
return true; | |
} | |
if (obj.__typename === typeCondition) { | |
return true; | |
} | |
warnOnceInDevelopment("You are using the simple (heuristic) fragment matcher, but your queries contain union or interface types.\n Apollo Client will not be able to able to accurately map fragments." + | |
"To make this error go away, use the IntrospectionFragmentMatcher as described in the docs: " + | |
"http://dev.apollodata.com/react/initialization.html#fragment-matcher", 'error'); | |
context.returnPartialData = true; | |
return true; | |
}; | |
return HeuristicFragmentMatcher; | |
}()); | |
var Deduplicator = (function () { | |
function Deduplicator(networkInterface) { | |
this.networkInterface = networkInterface; | |
this.inFlightRequestPromises = {}; | |
} | |
Deduplicator.prototype.query = function (request, deduplicate) { | |
var _this = this; | |
if (deduplicate === void 0) { deduplicate = true; } | |
if (!deduplicate) { | |
return this.networkInterface.query(request); | |
} | |
var key = this.getKey(request); | |
if (!this.inFlightRequestPromises[key]) { | |
this.inFlightRequestPromises[key] = this.networkInterface.query(request); | |
} | |
return this.inFlightRequestPromises[key] | |
.then(function (res) { | |
delete _this.inFlightRequestPromises[key]; | |
return res; | |
}) | |
.catch(function (err) { | |
delete _this.inFlightRequestPromises[key]; | |
throw err; | |
}); | |
}; | |
Deduplicator.prototype.getKey = function (request) { | |
return graphql_language_printer.print(request.query) + "|" + JSON.stringify(request.variables) + "|" + request.operationName; | |
}; | |
return Deduplicator; | |
}()); | |
var __assign$13 = (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 QueryStore = (function () { | |
function QueryStore() { | |
this.store = {}; | |
} | |
QueryStore.prototype.getStore = function () { | |
return this.store; | |
}; | |
QueryStore.prototype.get = function (queryId) { | |
return this.store[queryId]; | |
}; | |
QueryStore.prototype.initQuery = function (query) { | |
var previousQuery = this.store[query.queryId]; | |
if (previousQuery && previousQuery.queryString !== query.queryString) { | |
throw new Error('Internal Error: may not update existing query string in store'); | |
} | |
var isSetVariables = false; | |
var previousVariables = null; | |
if (query.storePreviousVariables && | |
previousQuery && | |
previousQuery.networkStatus !== exports.NetworkStatus.loading) { | |
if (!isEqual(previousQuery.variables, query.variables)) { | |
isSetVariables = true; | |
previousVariables = previousQuery.variables; | |
} | |
} | |
var networkStatus; | |
if (isSetVariables) { | |
networkStatus = exports.NetworkStatus.setVariables; | |
} | |
else if (query.isPoll) { | |
networkStatus = exports.NetworkStatus.poll; | |
} | |
else if (query.isRefetch) { | |
networkStatus = exports.NetworkStatus.refetch; | |
} | |
else { | |
networkStatus = exports.NetworkStatus.loading; | |
} | |
this.store[query.queryId] = { | |
queryString: query.queryString, | |
document: query.document, | |
variables: query.variables, | |
previousVariables: previousVariables, | |
networkError: null, | |
graphQLErrors: [], | |
networkStatus: networkStatus, | |
metadata: query.metadata, | |
}; | |
if (typeof query.fetchMoreForQueryId === 'string') { | |
this.store[query.fetchMoreForQueryId].networkStatus = | |
exports.NetworkStatus.fetchMore; | |
} | |
}; | |
QueryStore.prototype.markQueryResult = function (queryId, result, fetchMoreForQueryId) { | |
if (!this.store[queryId]) { | |
return; | |
} | |
this.store[queryId].networkError = null; | |
this.store[queryId].graphQLErrors = | |
result.errors && result.errors.length ? result.errors : []; | |
this.store[queryId].previousVariables = null; | |
this.store[queryId].networkStatus = exports.NetworkStatus.ready; | |
if (typeof fetchMoreForQueryId === 'string') { | |
this.store[fetchMoreForQueryId].networkStatus = exports.NetworkStatus.ready; | |
} | |
}; | |
QueryStore.prototype.markQueryError = function (queryId, error, fetchMoreForQueryId) { | |
if (!this.store[queryId]) { | |
return; | |
} | |
this.store[queryId].networkError = error; | |
this.store[queryId].networkStatus = exports.NetworkStatus.error; | |
if (typeof fetchMoreForQueryId === 'string') { | |
this.markQueryError(fetchMoreForQueryId, error, undefined); | |
} | |
}; | |
QueryStore.prototype.markQueryResultClient = function (queryId, complete) { | |
if (!this.store[queryId]) { | |
return; | |
} | |
this.store[queryId].networkError = null; | |
this.store[queryId].previousVariables = null; | |
this.store[queryId].networkStatus = complete | |
? exports.NetworkStatus.ready | |
: exports.NetworkStatus.loading; | |
}; | |
QueryStore.prototype.stopQuery = function (queryId) { | |
delete this.store[queryId]; | |
}; | |
QueryStore.prototype.reset = function (observableQueryIds) { | |
var _this = this; | |
this.store = Object.keys(this.store) | |
.filter(function (queryId) { | |
return observableQueryIds.indexOf(queryId) > -1; | |
}) | |
.reduce(function (res, key) { | |
res[key] = __assign$13({}, _this.store[key], { networkStatus: exports.NetworkStatus.loading }); | |
return res; | |
}, {}); | |
}; | |
return QueryStore; | |
}()); | |
function createStoreReducer(resultReducer, document, variables, config) { | |
return function (store, action) { | |
var _a = diffQueryAgainstStore({ | |
store: store, | |
query: document, | |
variables: variables, | |
returnPartialData: true, | |
fragmentMatcherFunction: config.fragmentMatcher, | |
config: config, | |
}), result = _a.result, isMissing = _a.isMissing; | |
if (isMissing) { | |
return store; | |
} | |
var nextResult; | |
try { | |
nextResult = resultReducer(result, action, variables); | |
} | |
catch (err) { | |
console.warn('Unhandled error in result reducer', err); | |
throw err; | |
} | |
if (result !== nextResult) { | |
return writeResultToStore({ | |
dataId: 'ROOT_QUERY', | |
result: nextResult, | |
store: store, | |
document: document, | |
variables: variables, | |
dataIdFromObject: config.dataIdFromObject, | |
fragmentMatcherFunction: config.fragmentMatcher, | |
}); | |
} | |
return store; | |
}; | |
} | |
var MutationStore = (function () { | |
function MutationStore() { | |
this.store = {}; | |
} | |
MutationStore.prototype.getStore = function () { | |
return this.store; | |
}; | |
MutationStore.prototype.get = function (mutationId) { | |
return this.store[mutationId]; | |
}; | |
MutationStore.prototype.initMutation = function (mutationId, mutationString, variables) { | |
this.store[mutationId] = { | |
mutationString: mutationString, | |
variables: variables || {}, | |
loading: true, | |
error: null, | |
}; | |
}; | |
MutationStore.prototype.markMutationError = function (mutationId, error) { | |
this.store[mutationId].loading = false; | |
this.store[mutationId].error = error; | |
}; | |
MutationStore.prototype.markMutationResult = function (mutationId) { | |
this.store[mutationId].loading = false; | |
this.store[mutationId].error = null; | |
}; | |
MutationStore.prototype.reset = function () { | |
this.store = {}; | |
}; | |
return MutationStore; | |
}()); | |
var __assign$14 = (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 QueryScheduler = (function () { | |
function QueryScheduler(_a) { | |
var queryManager = _a.queryManager; | |
this.queryManager = queryManager; | |
this.pollingTimers = {}; | |
this.inFlightQueries = {}; | |
this.registeredQueries = {}; | |
this.intervalQueries = {}; | |
} | |
QueryScheduler.prototype.checkInFlight = function (queryId) { | |
var query = this.queryManager.queryStore.get(queryId); | |
return (query && | |
query.networkStatus !== exports.NetworkStatus.ready && | |
query.networkStatus !== exports.NetworkStatus.error); | |
}; | |
QueryScheduler.prototype.fetchQuery = function (queryId, options, fetchType) { | |
var _this = this; | |
return new Promise(function (resolve, reject) { | |
_this.queryManager | |
.fetchQuery(queryId, options, fetchType) | |
.then(function (result) { | |
resolve(result); | |
}) | |
.catch(function (error) { | |
reject(error); | |
}); | |
}); | |
}; | |
QueryScheduler.prototype.startPollingQuery = function (options, queryId, listener) { | |
if (!options.pollInterval) { | |
throw new Error('Attempted to start a polling query without a polling interval.'); | |
} | |
if (this.queryManager.ssrMode) { | |
return queryId; | |
} | |
this.registeredQueries[queryId] = options; | |
if (listener) { | |
this.queryManager.addQueryListener(queryId, listener); | |
} | |
this.addQueryOnInterval(queryId, options); | |
return queryId; | |
}; | |
QueryScheduler.prototype.stopPollingQuery = function (queryId) { | |
delete this.registeredQueries[queryId]; | |
}; | |
QueryScheduler.prototype.fetchQueriesOnInterval = function (interval) { | |
var _this = this; | |
this.intervalQueries[interval] = this.intervalQueries[interval].filter(function (queryId) { | |
if (!_this.registeredQueries.hasOwnProperty(queryId)) { | |
return false; | |
} | |
if (_this.checkInFlight(queryId)) { | |
return true; | |
} | |
var queryOptions = _this.registeredQueries[queryId]; | |
var pollingOptions = __assign$14({}, queryOptions); | |
pollingOptions.fetchPolicy = 'network-only'; | |
_this.fetchQuery(queryId, pollingOptions, FetchType.poll); | |
return true; | |
}); | |
if (this.intervalQueries[interval].length === 0) { | |
clearInterval(this.pollingTimers[interval]); | |
delete this.intervalQueries[interval]; | |
} | |
}; | |
QueryScheduler.prototype.addQueryOnInterval = function (queryId, queryOptions) { | |
var _this = this; | |
var interval = queryOptions.pollInterval; | |
if (!interval) { | |
throw new Error("A poll interval is required to start polling query with id '" + queryId + "'."); | |
} | |
if (this.intervalQueries.hasOwnProperty(interval.toString()) && | |
this.intervalQueries[interval].length > 0) { | |
this.intervalQueries[interval].push(queryId); | |
} | |
else { | |
this.intervalQueries[interval] = [queryId]; | |
this.pollingTimers[interval] = setInterval(function () { | |
_this.fetchQueriesOnInterval(interval); | |
}, interval); | |
} | |
}; | |
QueryScheduler.prototype.registerPollingQuery = function (queryOptions) { | |
if (!queryOptions.pollInterval) { | |
throw new Error('Attempted to register a non-polling query with the scheduler.'); | |
} | |
return new ObservableQuery({ | |
scheduler: this, | |
options: queryOptions, | |
}); | |
}; | |
return QueryScheduler; | |
}()); | |
var __assign$12 = (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 QueryManager = (function () { | |
function QueryManager(_a) { | |
var networkInterface = _a.networkInterface, store = _a.store, reduxRootSelector = _a.reduxRootSelector, _b = _a.reducerConfig, reducerConfig = _b === void 0 ? {} : _b, fragmentMatcher = _a.fragmentMatcher, _c = _a.addTypename, addTypename = _c === void 0 ? true : _c, _d = _a.queryDeduplication, queryDeduplication = _d === void 0 ? false : _d, _e = _a.ssrMode, ssrMode = _e === void 0 ? false : _e; | |
var _this = this; | |
this.mutationStore = new MutationStore(); | |
this.queryStore = new QueryStore(); | |
this.idCounter = 1; | |
this.lastRequestId = {}; | |
this.disableBroadcasting = false; | |
this.networkInterface = networkInterface; | |
this.deduplicator = new Deduplicator(networkInterface); | |
this.store = store; | |
this.reduxRootSelector = reduxRootSelector; | |
this.reducerConfig = reducerConfig; | |
this.pollingTimers = {}; | |
this.queryListeners = {}; | |
this.queryDocuments = {}; | |
this.addTypename = addTypename; | |
this.queryDeduplication = queryDeduplication; | |
this.ssrMode = ssrMode; | |
if (typeof fragmentMatcher === 'undefined') { | |
this.fragmentMatcher = new HeuristicFragmentMatcher(); | |
} | |
else { | |
this.fragmentMatcher = fragmentMatcher; | |
} | |
this.scheduler = new QueryScheduler({ | |
queryManager: this, | |
}); | |
this.fetchQueryPromises = {}; | |
this.observableQueries = {}; | |
this.queryIdsByName = {}; | |
if (this.store['subscribe']) { | |
var currentStoreData_1; | |
this.store['subscribe'](function () { | |
var previousStoreData = currentStoreData_1 || {}; | |
var previousStoreHasData = Object.keys(previousStoreData).length; | |
currentStoreData_1 = _this.getApolloState(); | |
if (isEqual(previousStoreData, currentStoreData_1) && | |
previousStoreHasData) { | |
return; | |
} | |
_this.broadcastQueries(); | |
}); | |
} | |
} | |
QueryManager.prototype.broadcastNewStore = function (store) { | |
this.broadcastQueries(); | |
}; | |
QueryManager.prototype.mutate = function (_a) { | |
var _this = this; | |
var mutation = _a.mutation, variables = _a.variables, optimisticResponse = _a.optimisticResponse, updateQueriesByName = _a.updateQueries, _b = _a.refetchQueries, refetchQueries = _b === void 0 ? [] : _b, updateWithProxyFn = _a.update; | |
if (!mutation) { | |
throw new Error('mutation option is required. You must specify your GraphQL document in the mutation option.'); | |
} | |
var mutationId = this.generateQueryId(); | |
if (this.addTypename) { | |
mutation = addTypenameToDocument(mutation); | |
} | |
variables = assign({}, getDefaultValues(getMutationDefinition(mutation)), variables); | |
var mutationString = graphql_language_printer.print(mutation); | |
var request = { | |
query: mutation, | |
variables: variables, | |
operationName: getOperationName(mutation), | |
}; | |
this.queryDocuments[mutationId] = mutation; | |
var generateUpdateQueriesInfo = function () { | |
var ret = {}; | |
if (updateQueriesByName) { | |
Object.keys(updateQueriesByName).forEach(function (queryName) { | |
return (_this.queryIdsByName[queryName] || []).forEach(function (queryId) { | |
ret[queryId] = { | |
reducer: updateQueriesByName[queryName], | |
query: _this.queryStore.get(queryId), | |
}; | |
}); | |
}); | |
} | |
return ret; | |
}; | |
this.store.dispatch({ | |
type: 'APOLLO_MUTATION_INIT', | |
mutationString: mutationString, | |
mutation: mutation, | |
variables: variables || {}, | |
operationName: getOperationName(mutation), | |
mutationId: mutationId, | |
optimisticResponse: optimisticResponse, | |
extraReducers: this.getExtraReducers(), | |
updateQueries: generateUpdateQueriesInfo(), | |
update: updateWithProxyFn, | |
}); | |
this.mutationStore.initMutation(mutationId, mutationString, variables); | |
return new Promise(function (resolve, reject) { | |
_this.networkInterface | |
.query(request) | |
.then(function (result) { | |
if (result.errors) { | |
var error = new ApolloError({ | |
graphQLErrors: result.errors, | |
}); | |
_this.store.dispatch({ | |
type: 'APOLLO_MUTATION_ERROR', | |
error: error, | |
mutationId: mutationId, | |
}); | |
_this.mutationStore.markMutationError(mutationId, error); | |
delete _this.queryDocuments[mutationId]; | |
reject(error); | |
return; | |
} | |
_this.store.dispatch({ | |
type: 'APOLLO_MUTATION_RESULT', | |
result: result, | |
mutationId: mutationId, | |
document: mutation, | |
operationName: getOperationName(mutation), | |
variables: variables || {}, | |
extraReducers: _this.getExtraReducers(), | |
updateQueries: generateUpdateQueriesInfo(), | |
update: updateWithProxyFn, | |
}); | |
_this.mutationStore.markMutationResult(mutationId); | |
var reducerError = _this.getApolloState().reducerError; | |
if (reducerError && reducerError.mutationId === mutationId) { | |
reject(reducerError.error); | |
return; | |
} | |
if (typeof refetchQueries[0] === 'string') { | |
refetchQueries.forEach(function (name) { | |
_this.refetchQueryByName(name); | |
}); | |
} | |
else { | |
refetchQueries.forEach(function (pureQuery) { | |
_this.query({ | |
query: pureQuery.query, | |
variables: pureQuery.variables, | |
fetchPolicy: 'network-only', | |
}); | |
}); | |
} | |
delete _this.queryDocuments[mutationId]; | |
resolve(result); | |
}) | |
.catch(function (err) { | |
_this.store.dispatch({ | |
type: 'APOLLO_MUTATION_ERROR', | |
error: err, | |
mutationId: mutationId, | |
}); | |
delete _this.queryDocuments[mutationId]; | |
reject(new ApolloError({ | |
networkError: err, | |
})); | |
}); | |
}); | |
}; | |
QueryManager.prototype.fetchQuery = function (queryId, options, fetchType, fetchMoreForQueryId) { | |
var _this = this; | |
var _a = options.variables, variables = _a === void 0 ? {} : _a, _b = options.metadata, metadata = _b === void 0 ? null : _b, _c = options.fetchPolicy, fetchPolicy = _c === void 0 ? 'cache-first' : _c; | |
var queryDoc = this.transformQueryDocument(options).queryDoc; | |
var queryString = graphql_language_printer.print(queryDoc); | |
var storeResult; | |
var needToFetch = fetchPolicy === 'network-only'; | |
if (fetchType !== FetchType.refetch && fetchPolicy !== 'network-only') { | |
var _d = diffQueryAgainstStore({ | |
query: queryDoc, | |
store: this.reduxRootSelector(this.store.getState()).data, | |
variables: variables, | |
returnPartialData: true, | |
fragmentMatcherFunction: this.fragmentMatcher.match, | |
config: this.reducerConfig, | |
}), isMissing = _d.isMissing, result = _d.result; | |
needToFetch = isMissing || fetchPolicy === 'cache-and-network'; | |
storeResult = result; | |
} | |
var shouldFetch = needToFetch && fetchPolicy !== 'cache-only' && fetchPolicy !== 'standby'; | |
var requestId = this.generateRequestId(); | |
this.queryDocuments[queryId] = queryDoc; | |
this.queryStore.initQuery({ | |
queryId: queryId, | |
queryString: queryString, | |
document: queryDoc, | |
storePreviousVariables: shouldFetch, | |
variables: variables, | |
isPoll: fetchType === FetchType.poll, | |
isRefetch: fetchType === FetchType.refetch, | |
metadata: metadata, | |
fetchMoreForQueryId: fetchMoreForQueryId, | |
}); | |
this.broadcastQueries(); | |
if (QueryManager.EMIT_REDUX_ACTIONS) { | |
this.store.dispatch({ | |
type: 'APOLLO_QUERY_INIT', | |
queryString: queryString, | |
document: queryDoc, | |
operationName: getOperationName(queryDoc), | |
variables: variables, | |
fetchPolicy: fetchPolicy, | |
queryId: queryId, | |
requestId: requestId, | |
storePreviousVariables: shouldFetch, | |
isPoll: fetchType === FetchType.poll, | |
isRefetch: fetchType === FetchType.refetch, | |
fetchMoreForQueryId: fetchMoreForQueryId, | |
metadata: metadata, | |
}); | |
} | |
this.lastRequestId[queryId] = requestId; | |
var shouldDispatchClientResult = !shouldFetch || fetchPolicy === 'cache-and-network'; | |
if (shouldDispatchClientResult) { | |
this.queryStore.markQueryResultClient(queryId, !shouldFetch); | |
this.broadcastQueries(); | |
if (QueryManager.EMIT_REDUX_ACTIONS) { | |
this.store.dispatch({ | |
type: 'APOLLO_QUERY_RESULT_CLIENT', | |
result: { data: storeResult }, | |
variables: variables, | |
document: queryDoc, | |
operationName: getOperationName(queryDoc), | |
complete: !shouldFetch, | |
queryId: queryId, | |
requestId: requestId, | |
}); | |
} | |
} | |
if (shouldFetch) { | |
var networkResult = this.fetchRequest({ | |
requestId: requestId, | |
queryId: queryId, | |
document: queryDoc, | |
options: options, | |
fetchMoreForQueryId: fetchMoreForQueryId, | |
}).catch(function (error) { | |
if (isApolloError(error)) { | |
throw error; | |
} | |
else { | |
if (requestId >= (_this.lastRequestId[queryId] || 1)) { | |
if (QueryManager.EMIT_REDUX_ACTIONS) { | |
_this.store.dispatch({ | |
type: 'APOLLO_QUERY_ERROR', | |
error: error, | |
queryId: queryId, | |
requestId: requestId, | |
fetchMoreForQueryId: fetchMoreForQueryId, | |
}); | |
} | |
_this.queryStore.markQueryError(queryId, error, fetchMoreForQueryId); | |
_this.broadcastQueries(); | |
} | |
_this.removeFetchQueryPromise(requestId); | |
throw new ApolloError({ | |
networkError: error, | |
}); | |
} | |
}); | |
if (fetchPolicy !== 'cache-and-network') { | |
return networkResult; | |
} | |
} | |
return Promise.resolve({ data: storeResult }); | |
}; | |
QueryManager.prototype.queryListenerForObserver = function (queryId, options, observer) { | |
var _this = this; | |
var previouslyHadError = false; | |
return function (queryStoreValue) { | |
if (!queryStoreValue) { | |
return; | |
} | |
queryStoreValue = _this.queryStore.get(queryId); | |
var storedQuery = _this.observableQueries[queryId]; | |
var observableQuery = storedQuery ? storedQuery.observableQuery : null; | |
var fetchPolicy = observableQuery | |
? observableQuery.options.fetchPolicy | |
: options.fetchPolicy; | |
if (fetchPolicy === 'standby') { | |
return; | |
} | |
var lastResult = observableQuery | |
? observableQuery.getLastResult() | |
: null; | |
var shouldNotifyIfLoading = queryStoreValue.previousVariables || | |
fetchPolicy === 'cache-only' || | |
fetchPolicy === 'cache-and-network'; | |
var networkStatusChanged = lastResult && | |
queryStoreValue.networkStatus !== lastResult.networkStatus; | |
if (!isNetworkRequestInFlight(queryStoreValue.networkStatus) || | |
(networkStatusChanged && options.notifyOnNetworkStatusChange) || | |
shouldNotifyIfLoading) { | |
if ((queryStoreValue.graphQLErrors && | |
queryStoreValue.graphQLErrors.length > 0) || | |
queryStoreValue.networkError) { | |
var apolloError_1 = new ApolloError({ | |
graphQLErrors: queryStoreValue.graphQLErrors, | |
networkError: queryStoreValue.networkError, | |
}); | |
previouslyHadError = true; | |
if (observer.error) { | |
try { | |
observer.error(apolloError_1); | |
} | |
catch (e) { | |
setTimeout(function () { | |
throw e; | |
}, 0); | |
} | |
} | |
else { | |
setTimeout(function () { | |
throw apolloError_1; | |
}, 0); | |
if (!isProduction()) { | |
console.info('An unhandled error was thrown because no error handler is registered ' + | |
'for the query ' + | |
queryStoreValue.queryString); | |
} | |
} | |
} | |
else { | |
try { | |
var _a = diffQueryAgainstStore({ | |
store: _this.getDataWithOptimisticResults(), | |
query: _this.queryDocuments[queryId], | |
variables: queryStoreValue.previousVariables || queryStoreValue.variables, | |
config: _this.reducerConfig, | |
fragmentMatcherFunction: _this.fragmentMatcher.match, | |
previousResult: lastResult && lastResult.data, | |
}), data = _a.result, isMissing = _a.isMissing; | |
var resultFromStore = void 0; | |
if (isMissing && fetchPolicy !== 'cache-only') { | |
resultFromStore = { | |
data: lastResult && lastResult.data, | |
loading: isNetworkRequestInFlight(queryStoreValue.networkStatus), | |
networkStatus: queryStoreValue.networkStatus, | |
stale: true, | |
}; | |
} | |
else { | |
resultFromStore = { | |
data: data, | |
loading: isNetworkRequestInFlight(queryStoreValue.networkStatus), | |
networkStatus: queryStoreValue.networkStatus, | |
stale: false, | |
}; | |
} | |
if (observer.next) { | |
var isDifferentResult = !(lastResult && | |
resultFromStore && | |
lastResult.networkStatus === resultFromStore.networkStatus && | |
lastResult.stale === resultFromStore.stale && | |
lastResult.data === resultFromStore.data); | |
if (isDifferentResult || previouslyHadError) { | |
try { | |
observer.next(maybeDeepFreeze(resultFromStore)); | |
} | |
catch (e) { | |
setTimeout(function () { | |
throw e; | |
}, 0); | |
} | |
} | |
} | |
previouslyHadError = false; | |
} | |
catch (error) { | |
previouslyHadError = true; | |
if (observer.error) { | |
observer.error(new ApolloError({ | |
networkError: error, | |
})); | |
} | |
return; | |
} | |
} | |
} | |
}; | |
}; | |
QueryManager.prototype.watchQuery = function (options, shouldSubscribe) { | |
if (shouldSubscribe === void 0) { shouldSubscribe = true; } | |
if (options.returnPartialData) { | |
throw new Error('returnPartialData option is no longer supported since Apollo Client 1.0.'); | |
} | |
if (options.forceFetch) { | |
throw new Error('forceFetch option is no longer supported since Apollo Client 1.0. Use fetchPolicy instead.'); | |
} | |
if (options.noFetch) { | |
throw new Error('noFetch option is no longer supported since Apollo Client 1.0. Use fetchPolicy instead.'); | |
} | |
if (options.fetchPolicy === 'standby') { | |
throw new Error('client.watchQuery cannot be called with fetchPolicy set to "standby"'); | |
} | |
var queryDefinition = getQueryDefinition(options.query); | |
if (queryDefinition.variableDefinitions && | |
queryDefinition.variableDefinitions.length) { | |
var defaultValues = getDefaultValues(queryDefinition); | |
options.variables = assign({}, defaultValues, options.variables); | |
} | |
if (typeof options.notifyOnNetworkStatusChange === 'undefined') { | |
options.notifyOnNetworkStatusChange = false; | |
} | |
var transformedOptions = __assign$12({}, options); | |
var observableQuery = new ObservableQuery({ | |
scheduler: this.scheduler, | |
options: transformedOptions, | |
shouldSubscribe: shouldSubscribe, | |
}); | |
return observableQuery; | |
}; | |
QueryManager.prototype.query = function (options) { | |
var _this = this; | |
if (!options.query) { | |
throw new Error('query option is required. You must specify your GraphQL document in the query option.'); | |
} | |
if (options.query.kind !== 'Document') { | |
throw new Error('You must wrap the query string in a "gql" tag.'); | |
} | |
if (options.returnPartialData) { | |
throw new Error('returnPartialData option only supported on watchQuery.'); | |
} | |
if (options.pollInterval) { | |
throw new Error('pollInterval option only supported on watchQuery.'); | |
} | |
if (options.forceFetch) { | |
throw new Error('forceFetch option is no longer supported since Apollo Client 1.0. Use fetchPolicy instead.'); | |
} | |
if (options.noFetch) { | |
throw new Error('noFetch option is no longer supported since Apollo Client 1.0. Use fetchPolicy instead.'); | |
} | |
if (typeof options.notifyOnNetworkStatusChange !== 'undefined') { | |
throw new Error('Cannot call "query" with "notifyOnNetworkStatusChange" option. Only "watchQuery" has that option.'); | |
} | |
options.notifyOnNetworkStatusChange = false; | |
var requestId = this.idCounter; | |
var resPromise = new Promise(function (resolve, reject) { | |
_this.addFetchQueryPromise(requestId, resPromise, resolve, reject); | |
return _this.watchQuery(options, false) | |
.result() | |
.then(function (result) { | |
_this.removeFetchQueryPromise(requestId); | |
resolve(result); | |
}) | |
.catch(function (error) { | |
_this.removeFetchQueryPromise(requestId); | |
reject(error); | |
}); | |
}); | |
return resPromise; | |
}; | |
QueryManager.prototype.generateQueryId = function () { | |
var queryId = this.idCounter.toString(); | |
this.idCounter++; | |
return queryId; | |
}; | |
QueryManager.prototype.stopQueryInStore = function (queryId) { | |
this.queryStore.stopQuery(queryId); | |
this.broadcastQueries(); | |
if (QueryManager.EMIT_REDUX_ACTIONS) { | |
this.store.dispatch({ | |
type: 'APOLLO_QUERY_STOP', | |
queryId: queryId, | |
}); | |
} | |
}; | |
QueryManager.prototype.getApolloState = function () { | |
return this.reduxRootSelector(this.store.getState()); | |
}; | |
QueryManager.prototype.selectApolloState = function (store) { | |
return this.reduxRootSelector(store.getState()); | |
}; | |
QueryManager.prototype.getInitialState = function () { | |
return { data: this.getApolloState().data }; | |
}; | |
QueryManager.prototype.getDataWithOptimisticResults = function () { | |
return getDataWithOptimisticResults(this.getApolloState()); | |
}; | |
QueryManager.prototype.addQueryListener = function (queryId, listener) { | |
this.queryListeners[queryId] = this.queryListeners[queryId] || []; | |
this.queryListeners[queryId].push(listener); | |
}; | |
QueryManager.prototype.addFetchQueryPromise = function (requestId, promise, resolve, reject) { | |
this.fetchQueryPromises[requestId.toString()] = { | |
promise: promise, | |
resolve: resolve, | |
reject: reject, | |
}; | |
}; | |
QueryManager.prototype.removeFetchQueryPromise = function (requestId) { | |
delete this.fetchQueryPromises[requestId.toString()]; | |
}; | |
QueryManager.prototype.addObservableQuery = function (queryId, observableQuery) { | |
this.observableQueries[queryId] = { observableQuery: observableQuery }; | |
var queryDef = getQueryDefinition(observableQuery.options.query); | |
if (queryDef.name && queryDef.name.value) { | |
var queryName = queryDef.name.value; | |
this.queryIdsByName[queryName] = this.queryIdsByName[queryName] || []; | |
this.queryIdsByName[queryName].push(observableQuery.queryId); | |
} | |
}; | |
QueryManager.prototype.removeObservableQuery = function (queryId) { | |
var observableQuery = this.observableQueries[queryId].observableQuery; | |
var definition = getQueryDefinition(observableQuery.options.query); | |
var queryName = definition.name ? definition.name.value : null; | |
delete this.observableQueries[queryId]; | |
if (queryName) { | |
this.queryIdsByName[queryName] = this.queryIdsByName[queryName].filter(function (val) { | |
return !(observableQuery.queryId === val); | |
}); | |
} | |
}; | |
QueryManager.prototype.resetStore = function () { | |
var _this = this; | |
Object.keys(this.fetchQueryPromises).forEach(function (key) { | |
var reject = _this.fetchQueryPromises[key].reject; | |
reject(new Error('Store reset while query was in flight.')); | |
}); | |
this.queryStore.reset(Object.keys(this.observableQueries)); | |
this.store.dispatch({ | |
type: 'APOLLO_STORE_RESET', | |
observableQueryIds: Object.keys(this.observableQueries), | |
}); | |
this.mutationStore.reset(); | |
var observableQueryPromises = []; | |
Object.keys(this.observableQueries).forEach(function (queryId) { | |
var storeQuery = _this.queryStore.get(queryId); | |
var fetchPolicy = _this.observableQueries[queryId].observableQuery | |
.options.fetchPolicy; | |
if (fetchPolicy !== 'cache-only' && fetchPolicy !== 'standby') { | |
observableQueryPromises.push(_this.observableQueries[queryId].observableQuery.refetch()); | |
} | |
}); | |
return Promise.all(observableQueryPromises); | |
}; | |
QueryManager.prototype.startQuery = function (queryId, options, listener) { | |
this.addQueryListener(queryId, listener); | |
this.fetchQuery(queryId, options) | |
.catch(function (error) { return undefined; }); | |
return queryId; | |
}; | |
QueryManager.prototype.startGraphQLSubscription = function (options) { | |
var _this = this; | |
var query = options.query; | |
var transformedDoc = query; | |
if (this.addTypename) { | |
transformedDoc = addTypenameToDocument(transformedDoc); | |
} | |
var variables = assign({}, getDefaultValues(getOperationDefinition(query)), options.variables); | |
var request = { | |
query: transformedDoc, | |
variables: variables, | |
operationName: getOperationName(transformedDoc), | |
}; | |
var subId; | |
var observers = []; | |
return new Observable(function (observer) { | |
observers.push(observer); | |
if (observers.length === 1) { | |
var handler = function (error, result) { | |
if (error) { | |
observers.forEach(function (obs) { | |
if (obs.error) { | |
obs.error(error); | |
} | |
}); | |
} | |
else { | |
_this.store.dispatch({ | |
type: 'APOLLO_SUBSCRIPTION_RESULT', | |
document: transformedDoc, | |
operationName: getOperationName(transformedDoc), | |
result: { data: result }, | |
variables: variables, | |
subscriptionId: subId, | |
extraReducers: _this.getExtraReducers(), | |
}); | |
observers.forEach(function (obs) { | |
if (obs.next) { | |
obs.next(result); | |
} | |
}); | |
} | |
}; | |
subId = _this | |
.networkInterface.subscribe(request, handler); | |
} | |
return { | |
unsubscribe: function () { | |
observers = observers.filter(function (obs) { return obs !== observer; }); | |
if (observers.length === 0) { | |
_this.networkInterface.unsubscribe(subId); | |
} | |
}, | |
_networkSubscriptionId: subId, | |
}; | |
}); | |
}; | |
QueryManager.prototype.removeQuery = function (queryId) { | |
delete this.queryListeners[queryId]; | |
delete this.queryDocuments[queryId]; | |
}; | |
QueryManager.prototype.stopQuery = function (queryId) { | |
this.removeQuery(queryId); | |
this.stopQueryInStore(queryId); | |
}; | |
QueryManager.prototype.getCurrentQueryResult = function (observableQuery, isOptimistic) { | |
if (isOptimistic === void 0) { isOptimistic = false; } | |
var _a = this.getQueryParts(observableQuery), variables = _a.variables, document = _a.document; | |
var lastResult = observableQuery.getLastResult(); | |
var queryOptions = observableQuery.options; | |
var readOptions = { | |
store: isOptimistic | |
? this.getDataWithOptimisticResults() | |
: this.getApolloState().data, | |
query: document, | |
variables: variables, | |
config: this.reducerConfig, | |
previousResult: lastResult ? lastResult.data : undefined, | |
fragmentMatcherFunction: this.fragmentMatcher.match, | |
}; | |
try { | |
var data = readQueryFromStore(readOptions); | |
return maybeDeepFreeze({ data: data, partial: false }); | |
} | |
catch (e) { | |
return maybeDeepFreeze({ data: {}, partial: true }); | |
} | |
}; | |
QueryManager.prototype.getQueryWithPreviousResult = function (queryIdOrObservable, isOptimistic) { | |
if (isOptimistic === void 0) { isOptimistic = false; } | |
var observableQuery; | |
if (typeof queryIdOrObservable === 'string') { | |
if (!this.observableQueries[queryIdOrObservable]) { | |
throw new Error("ObservableQuery with this id doesn't exist: " + queryIdOrObservable); | |
} | |
observableQuery = this.observableQueries[queryIdOrObservable] | |
.observableQuery; | |
} | |
else { | |
observableQuery = queryIdOrObservable; | |
} | |
var _a = this.getQueryParts(observableQuery), variables = _a.variables, document = _a.document; | |
var data = this.getCurrentQueryResult(observableQuery, isOptimistic).data; | |
return { | |
previousResult: data, | |
variables: variables, | |
document: document, | |
}; | |
}; | |
QueryManager.prototype.getQueryParts = function (observableQuery) { | |
var queryOptions = observableQuery.options; | |
var transformedDoc = observableQuery.options.query; | |
if (this.addTypename) { | |
transformedDoc = addTypenameToDocument(transformedDoc); | |
} | |
return { | |
variables: queryOptions.variables, | |
document: transformedDoc, | |
}; | |
}; | |
QueryManager.prototype.transformQueryDocument = function (options) { | |
var queryDoc = options.query; | |
if (this.addTypename) { | |
queryDoc = addTypenameToDocument(queryDoc); | |
} | |
return { | |
queryDoc: queryDoc, | |
}; | |
}; | |
QueryManager.prototype.getExtraReducers = function () { | |
var _this = this; | |
return Object.keys(this.observableQueries) | |
.map(function (obsQueryId) { | |
var query = _this.observableQueries[obsQueryId].observableQuery; | |
var queryOptions = query.options; | |
if (queryOptions.reducer) { | |
return createStoreReducer(queryOptions.reducer, _this.addTypename | |
? addTypenameToDocument(queryOptions.query) | |
: queryOptions.query, query.variables || {}, _this.reducerConfig); | |
} | |
return null; | |
}) | |
.filter(function (reducer) { return reducer !== null; }); | |
}; | |
QueryManager.prototype.fetchRequest = function (_a) { | |
var _this = this; | |
var requestId = _a.requestId, queryId = _a.queryId, document = _a.document, options = _a.options, fetchMoreForQueryId = _a.fetchMoreForQueryId; | |
var variables = options.variables; | |
var request = { | |
query: document, | |
variables: variables, | |
operationName: getOperationName(document), | |
}; | |
var retPromise = new Promise(function (resolve, reject) { | |
_this.addFetchQueryPromise(requestId, retPromise, resolve, reject); | |
_this.deduplicator | |
.query(request, _this.queryDeduplication) | |
.then(function (result) { | |
var extraReducers = _this.getExtraReducers(); | |
if (requestId >= (_this.lastRequestId[queryId] || 1)) { | |
_this.disableBroadcasting = true; | |
_this.store.dispatch({ | |
type: 'APOLLO_QUERY_RESULT', | |
document: document, | |
variables: variables ? variables : {}, | |
operationName: getOperationName(document), | |
result: result, | |
queryId: queryId, | |
requestId: requestId, | |
fetchMoreForQueryId: fetchMoreForQueryId, | |
extraReducers: extraReducers, | |
}); | |
_this.disableBroadcasting = false; | |
var reducerError = _this.getApolloState().reducerError; | |
if (!reducerError || reducerError.queryId !== queryId) { | |
_this.queryStore.markQueryResult(queryId, result, fetchMoreForQueryId); | |
_this.broadcastQueries(); | |
} | |
} | |
_this.removeFetchQueryPromise(requestId); | |
if (result.errors) { | |
throw new ApolloError({ | |
graphQLErrors: result.errors, | |
}); | |
} | |
return result; | |
}) | |
.then(function (result) { | |
var resultFromStore; | |
if (fetchMoreForQueryId) { | |
resultFromStore = result.data; | |
} | |
else { | |
try { | |
resultFromStore = readQueryFromStore({ | |
store: _this.getApolloState().data, | |
variables: variables, | |
query: document, | |
config: _this.reducerConfig, | |
fragmentMatcherFunction: _this.fragmentMatcher.match, | |
}); | |
} | |
catch (e) { } | |
} | |
var reducerError = _this.getApolloState().reducerError; | |
if (reducerError && reducerError.queryId === queryId) { | |
return Promise.reject(reducerError.error); | |
} | |
_this.removeFetchQueryPromise(requestId); | |
resolve({ | |
data: resultFromStore, | |
loading: false, | |
networkStatus: exports.NetworkStatus.ready, | |
stale: false, | |
}); | |
return Promise.resolve(); | |
}) | |
.catch(function (error) { | |
reject(error); | |
}); | |
}); | |
return retPromise; | |
}; | |
QueryManager.prototype.refetchQueryByName = function (queryName) { | |
var _this = this; | |
var refetchedQueries = this.queryIdsByName[queryName]; | |
if (refetchedQueries === undefined) { | |
console.warn("Warning: unknown query with name " + queryName + " asked to refetch"); | |
return; | |
} | |
else { | |
return Promise.all(refetchedQueries.map(function (queryId) { | |
return _this.observableQueries[queryId].observableQuery.refetch(); | |
})); | |
} | |
}; | |
QueryManager.prototype.broadcastQueries = function () { | |
var _this = this; | |
if (this.disableBroadcasting) { | |
return; | |
} | |
Object.keys(this.queryListeners).forEach(function (queryId) { | |
var listeners = _this.queryListeners[queryId]; | |
if (listeners) { | |
listeners.forEach(function (listener) { | |
if (listener) { | |
var queryStoreValue = _this.queryStore.get(queryId); | |
listener(queryStoreValue); | |
} | |
}); | |
} | |
}); | |
}; | |
QueryManager.prototype.generateRequestId = function () { | |
var requestId = this.idCounter; | |
this.idCounter++; | |
return requestId; | |
}; | |
QueryManager.EMIT_REDUX_ACTIONS = true; | |
return QueryManager; | |
}()); | |
var version = "1.9.0"; | |
var __assign$11 = (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 DEFAULT_REDUX_ROOT_KEY = 'apollo'; | |
function defaultReduxRootSelector(state) { | |
return state[DEFAULT_REDUX_ROOT_KEY]; | |
} | |
function defaultDataIdFromObject(result) { | |
if (result.__typename) { | |
if (result.id !== undefined) { | |
return result.__typename + ":" + result.id; | |
} | |
if (result._id !== undefined) { | |
return result.__typename + ":" + result._id; | |
} | |
} | |
return null; | |
} | |
var hasSuggestedDevtools = false; | |
var ApolloClient$1 = (function () { | |
function ApolloClient(options) { | |
if (options === void 0) { options = {}; } | |
var _this = this; | |
this.middleware = function () { | |
return function (store) { | |
_this.setStore(store); | |
return function (next) { return function (action) { | |
var previousApolloState = _this.queryManager.selectApolloState(store); | |
var returnValue = next(action); | |
var newApolloState = _this.queryManager.selectApolloState(store); | |
if (newApolloState !== previousApolloState) { | |
_this.queryManager.broadcastNewStore(store.getState()); | |
} | |
if (_this.devToolsHookCb) { | |
_this.devToolsHookCb({ | |
action: action, | |
state: { | |
queries: _this.queryManager.queryStore.getStore(), | |
mutations: _this.queryManager.mutationStore.getStore(), | |
}, | |
dataWithOptimisticResults: _this.queryManager.getDataWithOptimisticResults(), | |
}); | |
} | |
return returnValue; | |
}; }; | |
}; | |
}; | |
var dataIdFromObject = options.dataIdFromObject; | |
var networkInterface = options.networkInterface, reduxRootSelector = options.reduxRootSelector, initialState = options.initialState, _a = options.ssrMode, ssrMode = _a === void 0 ? false : _a, _b = options.ssrForceFetchDelay, ssrForceFetchDelay = _b === void 0 ? 0 : _b, _c = options.addTypename, addTypename = _c === void 0 ? true : _c, customResolvers = options.customResolvers, connectToDevTools = options.connectToDevTools, fragmentMatcher = options.fragmentMatcher, _d = options.queryDeduplication, queryDeduplication = _d === void 0 ? true : _d; | |
if (typeof reduxRootSelector === 'function') { | |
this.reduxRootSelector = reduxRootSelector; | |
} | |
else if (typeof reduxRootSelector !== 'undefined') { | |
throw new Error('"reduxRootSelector" must be a function.'); | |
} | |
if (typeof fragmentMatcher === 'undefined') { | |
this.fragmentMatcher = new HeuristicFragmentMatcher(); | |
} | |
else { | |
this.fragmentMatcher = fragmentMatcher; | |
} | |
var createQuery = function (getResult) { | |
var resolved = false; | |
return function (request) { | |
return new Promise(function (resolve, reject) { | |
var subscription = getResult(request).subscribe({ | |
next: function (data) { | |
if (!resolved) { | |
resolve(data); | |
resolved = true; | |
} | |
else { | |
console.warn('Apollo Client does not support multiple results from an Observable'); | |
} | |
}, | |
error: reject, | |
complete: function () { return subscription.unsubscribe(); }, | |
}); | |
}); | |
}; | |
}; | |
if (networkInterface instanceof apolloLinkCore.ApolloLink) { | |
this.networkInterface = { | |
query: createQuery(function (request) { | |
return apolloLinkCore.execute(networkInterface, request); | |
}), | |
}; | |
} | |
else if (networkInterface && | |
typeof networkInterface.request === | |
'function') { | |
console.warn("The Observable Network interface will be deprecated"); | |
this.networkInterface = __assign$11({}, networkInterface, { query: createQuery(networkInterface.request) }); | |
} | |
else { | |
this.networkInterface = networkInterface | |
? networkInterface | |
: createNetworkInterface({ uri: '/graphql' }); | |
} | |
this.initialState = initialState ? initialState : {}; | |
this.addTypename = addTypename; | |
this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0; | |
this.dataId = dataIdFromObject = | |
dataIdFromObject || defaultDataIdFromObject; | |
this.dataIdFromObject = this.dataId; | |
this.fieldWithArgs = getStoreKeyName; | |
this.queryDeduplication = queryDeduplication; | |
this.ssrMode = ssrMode; | |
if (ssrForceFetchDelay) { | |
setTimeout(function () { return (_this.disableNetworkFetches = false); }, ssrForceFetchDelay); | |
} | |
this.reducerConfig = { | |
dataIdFromObject: dataIdFromObject, | |
customResolvers: customResolvers, | |
addTypename: addTypename, | |
fragmentMatcher: this.fragmentMatcher.match, | |
}; | |
this.watchQuery = this.watchQuery.bind(this); | |
this.query = this.query.bind(this); | |
this.mutate = this.mutate.bind(this); | |
this.setStore = this.setStore.bind(this); | |
this.resetStore = this.resetStore.bind(this); | |
var defaultConnectToDevTools = !isProduction() && | |
typeof window !== 'undefined' && | |
!window.__APOLLO_CLIENT__; | |
if (typeof connectToDevTools === 'undefined' | |
? defaultConnectToDevTools | |
: connectToDevTools) { | |
window.__APOLLO_CLIENT__ = this; | |
} | |
if (!hasSuggestedDevtools && !isProduction()) { | |
hasSuggestedDevtools = true; | |
if (typeof window !== 'undefined' && | |
window.document && | |
window.top === window.self) { | |
if (typeof window.__APOLLO_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { | |
if (navigator.userAgent.indexOf('Chrome') > -1) { | |
console.debug('Download the Apollo DevTools ' + | |
'for a better development experience: ' + | |
'https://chrome.google.com/webstore/detail/apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm'); | |
} | |
} | |
} | |
} | |
this.version = version; | |
} | |
ApolloClient.prototype.watchQuery = function (options) { | |
this.initStore(); | |
if (this.disableNetworkFetches && options.fetchPolicy === 'network-only') { | |
options = __assign$11({}, options, { fetchPolicy: 'cache-first' }); | |
} | |
return this.queryManager.watchQuery(options); | |
}; | |
ApolloClient.prototype.query = function (options) { | |
this.initStore(); | |
if (options.fetchPolicy === 'cache-and-network') { | |
throw new Error('cache-and-network fetchPolicy can only be used with watchQuery'); | |
} | |
if (this.disableNetworkFetches && options.fetchPolicy === 'network-only') { | |
options = __assign$11({}, options, { fetchPolicy: 'cache-first' }); | |
} | |
return this.queryManager.query(options); | |
}; | |
ApolloClient.prototype.mutate = function (options) { | |
this.initStore(); | |
return this.queryManager.mutate(options); | |
}; | |
ApolloClient.prototype.subscribe = function (options) { | |
this.initStore(); | |
return this.queryManager.startGraphQLSubscription(options); | |
}; | |
ApolloClient.prototype.readQuery = function (options) { | |
return this.initProxy().readQuery(options); | |
}; | |
ApolloClient.prototype.readFragment = function (options) { | |
return this.initProxy().readFragment(options); | |
}; | |
ApolloClient.prototype.writeQuery = function (options) { | |
return this.initProxy().writeQuery(options); | |
}; | |
ApolloClient.prototype.writeFragment = function (options) { | |
return this.initProxy().writeFragment(options); | |
}; | |
ApolloClient.prototype.reducer = function () { | |
return createApolloReducer(this.reducerConfig); | |
}; | |
ApolloClient.prototype.__actionHookForDevTools = function (cb) { | |
this.devToolsHookCb = cb; | |
}; | |
ApolloClient.prototype.initStore = function () { | |
var _this = this; | |
if (this.store) { | |
return; | |
} | |
if (this.reduxRootSelector) { | |
throw new Error('Cannot initialize the store because "reduxRootSelector" is provided. ' + | |
'reduxRootSelector should only be used when the store is created outside of the client. ' + | |
'This may lead to unexpected results when querying the store internally. ' + | |
"Please remove that option from ApolloClient constructor."); | |
} | |
this.setStore(createApolloStore({ | |
reduxRootKey: DEFAULT_REDUX_ROOT_KEY, | |
initialState: this.initialState, | |
config: this.reducerConfig, | |
logger: function (store) { return function (next) { return function (action) { | |
var result = next(action); | |
if (_this.devToolsHookCb) { | |
_this.devToolsHookCb({ | |
action: action, | |
state: { | |
queries: _this.queryManager.queryStore.getStore(), | |
mutations: _this.queryManager.mutationStore.getStore(), | |
}, | |
dataWithOptimisticResults: _this.queryManager.getDataWithOptimisticResults(), | |
}); | |
} | |
return result; | |
}; }; }, | |
})); | |
}; | |
ApolloClient.prototype.resetStore = function () { | |
return this.queryManager ? this.queryManager.resetStore() : null; | |
}; | |
ApolloClient.prototype.getInitialState = function () { | |
this.initStore(); | |
return this.queryManager.getInitialState(); | |
}; | |
ApolloClient.prototype.setStore = function (store) { | |
var reduxRootSelector; | |
if (this.reduxRootSelector) { | |
reduxRootSelector = this.reduxRootSelector; | |
} | |
else { | |
reduxRootSelector = defaultReduxRootSelector; | |
} | |
if (typeof reduxRootSelector(store.getState()) === 'undefined') { | |
throw new Error('Existing store does not use apolloReducer. Please make sure the store ' + | |
'is properly configured and "reduxRootSelector" is correctly specified.'); | |
} | |
this.store = store; | |
this.queryManager = new QueryManager({ | |
networkInterface: this.networkInterface, | |
reduxRootSelector: reduxRootSelector, | |
store: store, | |
addTypename: this.addTypename, | |
reducerConfig: this.reducerConfig, | |
queryDeduplication: this.queryDeduplication, | |
fragmentMatcher: this.fragmentMatcher, | |
ssrMode: this.ssrMode, | |
}); | |
}; | |
ApolloClient.prototype.initProxy = function () { | |
if (!this.proxy) { | |
this.initStore(); | |
this.proxy = new ReduxDataProxy(this.store, this.reduxRootSelector || defaultReduxRootSelector, this.fragmentMatcher, this.reducerConfig); | |
} | |
return this.proxy; | |
}; | |
return ApolloClient; | |
}()); | |
exports.createNetworkInterface = createNetworkInterface; | |
exports.createBatchingNetworkInterface = createBatchingNetworkInterface; | |
exports.createApolloStore = createApolloStore; | |
exports.createApolloReducer = createApolloReducer; | |
exports.readQueryFromStore = readQueryFromStore; | |
exports.writeQueryToStore = writeQueryToStore; | |
exports.addTypenameToDocument = addTypenameToDocument; | |
exports.createFragmentMap = createFragmentMap; | |
exports.ApolloError = ApolloError; | |
exports.getQueryDefinition = getQueryDefinition; | |
exports.getMutationDefinition = getMutationDefinition; | |
exports.getFragmentDefinitions = getFragmentDefinitions; | |
exports.toIdValue = toIdValue; | |
exports.IntrospectionFragmentMatcher = IntrospectionFragmentMatcher; | |
exports.printAST = graphql_language_printer.print; | |
exports.HTTPFetchNetworkInterface = HTTPFetchNetworkInterface; | |
exports.HTTPBatchedNetworkInterface = HTTPBatchedNetworkInterface; | |
exports.ObservableQuery = ObservableQuery; | |
exports.ApolloClient = ApolloClient$1; | |
exports['default'] = ApolloClient$1; | |
Object.defineProperty(exports, '__esModule', { value: true }); | |
}))); | |
//# sourceMappingURL=apollo.umd.js.map |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment