UNPKG

apollo-client-cors-hack

Version:

A simple yet functional GraphQL client.

1,292 lines (1,274 loc) 146 kB
(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')) : typeof define === 'function' && define.amd ? define(['exports', 'whatwg-fetch', 'graphql/language/printer', 'redux', 'graphql-anywhere', 'symbol-observable'], factory) : (factory((global.apollo = global.apollo || {}),null,global.graphql_language_printer,global.redux,global.graphqlAnywhere,global.$$observable)); }(this, (function (exports,whatwgFetch,graphql_language_printer,redux,graphqlAnywhere,$$observable) { 'use strict'; graphqlAnywhere = 'default' in graphqlAnywhere ? graphqlAnywhere['default'] : graphqlAnywhere; $$observable = 'default' in $$observable ? $$observable['default'] : $$observable; 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) { 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') && !payload.hasOwnProperty('body')) { throw new Error("Server response was missing for query '" + request.debugName + "'."); } else { if (payload.hasOwnProperty('body')) { return JSON.parse(payload.body); } 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; uri = uriOrInterfaceOpts; } else { opts = uriOrInterfaceOpts.opts; uri = uriOrInterfaceOpts.uri; } return new HTTPFetchNetworkInterface(uri, opts); } var QueryBatcher = (function () { function QueryBatcher(_a) { var batchInterval = _a.batchInterval, batchFetchFunction = _a.batchFetchFunction; this.queuedRequests = []; this.queuedRequests = []; this.batchInterval = batchInterval; 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(); } 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 () { _this.consumeQueue(); }, this.batchInterval); }; return QueryBatcher; }()); 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 __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$1 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; var HTTPBatchedNetworkInterface = (function (_super) { __extends$1(HTTPBatchedNetworkInterface, _super); function HTTPBatchedNetworkInterface(uri, batchInterval, fetchOpts) { var _this = _super.call(this, uri, fetchOpts) || this; if (typeof batchInterval !== 'number') { throw new Error("batchInterval must be a number, got " + batchInterval); } _this.batcher = new QueryBatcher({ batchInterval: batchInterval, 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$1({}, this._opts); var middlewarePromise = this.applyBatchMiddlewares({ requests: requests, options: options, }); return new Promise(function (resolve, reject) { middlewarePromise.then(function (batchRequestAndOptions) { return _this.batchedFetchFromRemoteEndpoint(batchRequestAndOptions) .then(function (result) { var httpResponse = result; if (!httpResponse.ok) { return _this.applyBatchAfterwares({ responses: [httpResponse], options: batchRequestAndOptions }) .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$1({}, this._opts, { body: JSON.stringify(printedRequests), method: 'POST' }, options, { headers: __assign$1({ 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(options.uri, options.batchInterval, options.opts || {}); } function isQueryResultAction(action) { return action.type === 'APOLLO_QUERY_RESULT'; } function isQueryErrorAction(action) { return action.type === 'APOLLO_QUERY_ERROR'; } function isQueryInitAction(action) { return action.type === 'APOLLO_QUERY_INIT'; } function isQueryResultClientAction(action) { return action.type === 'APOLLO_QUERY_RESULT_CLIENT'; } function isQueryStopAction(action) { return action.type === 'APOLLO_QUERY_STOP'; } function isMutationInitAction(action) { return action.type === 'APOLLO_MUTATION_INIT'; } function isMutationResultAction(action) { return action.type === 'APOLLO_MUTATION_RESULT'; } function isMutationErrorAction(action) { return action.type === 'APOLLO_MUTATION_ERROR'; } function isUpdateQueryResultAction(action) { return action.type === 'APOLLO_UPDATE_QUERY_RESULT'; } function isStoreResetAction(action) { return action.type === 'APOLLO_STORE_RESET'; } function isSubscriptionResultAction(action) { return action.type === 'APOLLO_SUBSCRIPTION_RESULT'; } function isWriteAction(action) { return action.type === 'APOLLO_WRITE'; } function isStringValue(value) { return value.kind === 'StringValue'; } function isBooleanValue(value) { return value.kind === 'BooleanValue'; } function isIntValue(value) { return value.kind === 'IntValue'; } function isFloatValue(value) { return value.kind === 'FloatValue'; } function isVariable(value) { return value.kind === 'Variable'; } function isObjectValue(value) { return value.kind === 'ObjectValue'; } function isListValue(value) { return value.kind === 'ListValue'; } function isEnumValue(value) { return value.kind === 'EnumValue'; } function valueToObjectRepresentation(argObj, name, value, variables) { if (isIntValue(value) || isFloatValue(value)) { argObj[name.value] = Number(value.value); } else if (isBooleanValue(value) || isStringValue(value)) { argObj[name.value] = value.value; } else if (isObjectValue(value)) { var nestedArgObj_1 = {}; value.fields.map(function (obj) { return valueToObjectRepresentation(nestedArgObj_1, obj.name, obj.value, variables); }); argObj[name.value] = nestedArgObj_1; } else if (isVariable(value)) { var variableValue = (variables || {})[value.name.value]; argObj[name.value] = variableValue; } else if (isListValue(value)) { argObj[name.value] = value.values.map(function (listValue) { var nestedArgArrayObj = {}; valueToObjectRepresentation(nestedArgArrayObj, name, listValue, variables); return nestedArgArrayObj[name.value]; }); } else if (isEnumValue(value)) { argObj[name.value] = value.value; } else { throw new Error("The inline argument \"" + name.value + "\" of kind \"" + value.kind + "\" is not supported.\n Use variables instead of inline arguments to overcome this limitation."); } } function storeKeyNameFromField(field, variables) { if (field.arguments && field.arguments.length) { var argObj_1 = {}; field.arguments.forEach(function (_a) { var name = _a.name, value = _a.value; return valueToObjectRepresentation(argObj_1, name, value, variables); }); return storeKeyNameFromFieldNameAndArgs(field.name.value, argObj_1); } return field.name.value; } function storeKeyNameFromFieldNameAndArgs(fieldName, args) { if (args) { var stringifiedArgs = JSON.stringify(args); return fieldName + "(" + stringifiedArgs + ")"; } return fieldName; } function resultKeyNameFromField(field) { return field.alias ? field.alias.value : field.name.value; } function isField(selection) { return selection.kind === 'Field'; } function isInlineFragment(selection) { return selection.kind === 'InlineFragment'; } function graphQLResultHasError(result) { return result.errors && result.errors.length; } function isIdValue(idObject) { return (idObject != null && typeof idObject === 'object' && idObject.type === 'id'); } function toIdValue(id, generated) { if (generated === void 0) { generated = false; } return { type: 'id', id: id, generated: generated, }; } function isJsonValue(jsonObject) { return (jsonObject != null && typeof jsonObject === 'object' && jsonObject.type === 'json'); } var __assign$5 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; function 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 = ''; 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$5({}, 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 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$4 = (undefined && undefined.__assign) || Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; var 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 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); return writeSelectionSetToStore({ dataId: 'ROOT_QUERY', result: result, selectionSet: queryDefinition.selectionSet, context: { store: store, variables: variables, dataIdFromObject: dataIdFromObject, fragmentMap: fragmentMap, fragmentMatcherFunction: fragmentMatcherFunction, }, }); } 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, variables: variables, dataIdFromObject: dataIdFromObject, fragmentMap: fragmentMap, fragmentMatcherFunction: fragmentMatcherFunction, }, }); } catch (e) { var e2 = new Error("Error writing result to store for query " + (document.loc && document.loc.source.body)); e2.message += '/n' + e.message; e2.stack = e.stack; throw e2; } } 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); } } } } } 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$4({}, generated, real); }); } function writeFieldToStore(_a) { var field = _a.field, value = _a.value, dataId = _a.dataId, context = _a.context; var variables = context.variables, dataIdFromObject = context.dataIdFromObject, store = context.store, fragmentMap = context.fragmentMap; var storeValue; var storeFieldName = storeKeyNameFromField(field, variables); var shouldMerge = false; var generatedKey = ''; if (!field.selectionSet || value === null) { storeValue = value != null && typeof value === 'object' ? { type: 'json', json: value } : value; } else if (Array.isArray(value)) { var generatedId = dataId + "." + storeFieldName; storeValue = processArrayValue(value, generatedId, field.selectionSet, context); } else { var valueDataId = dataId + "." + storeFieldName; var generated = true; if (!isGeneratedId(valueDataId)) { valueDataId = '$' + valueDataId; } if (dataIdFromObject) { var semanticId = dataIdFromObject(value); if (semanticId && isGeneratedId(semanticId)) { throw new Error('IDs returned by dataIdFromObject cannot begin with the "$" character.'); } if (semanticId) { valueDataId = semanticId; generated = false; } } writeSelectionSetToStore({ dataId: valueDataId, result: value, selectionSet: field.selectionSet, context: context, }); storeValue = { type: 'id', id: valueDataId, generated: generated, }; if (store[dataId] && store[dataId][storeFieldName] !== storeValue) { var escapedId = store[dataId][storeFieldName]; if (isIdValue(storeValue) && storeValue.generated && isIdValue(escapedId) && !escapedId.generated) { throw new Error("Store error: the application attempted to write an object with no provided id" + (" but the store already contains an id of " + escapedId.id + " for this object.")); } if (isIdValue(escapedId) && escapedId.generated) { generatedKey = escapedId.id; shouldMerge = true; } } } var newStoreObj = __assign$4({}, store[dataId], (_b = {}, _b[storeFieldName] = storeValue, _b)); if (shouldMerge) { mergeWithGenerated(generatedKey, storeValue.id, store); } if (!store[dataId] || storeValue !== store[dataId][storeFieldName]) { store[dataId] = newStoreObj; } var _b; } function processArrayValue(value, generatedId, selectionSet, context) { return value.map(function (item, index) { if (item === null) { return null; } var itemDataId = generatedId + "." + index; if (Array.isArray(item)) { return processArrayValue(item, itemDataId, selectionSet, context); } var generated = true; if (context.dataIdFromObject) { var semanticId = context.dataIdFromObject(item); if (semanticId) { itemDataId = semanticId; generated = false; } } writeSelectionSetToStore({ dataId: itemDataId, result: item, selectionSet: selectionSet, context: context, }); var idStoreValue = { type: 'id', id: itemDataId, generated: generated, }; return idStoreValue; }); } var __assign$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 fakeMutationResultAction = { type: 'APOLLO_MUTATION_RESULT', result: { data: action.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, queries, mutations, 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; assertIdValue(idValue); var objId = idValue.id; var obj = context.store[objId]; var storeKeyName = storeKeyNameFromFieldNameAndArgs(fieldName, args); var fieldValue = (obj || {})[storeKeyName]; if (typeof fieldValue === 'undefined') { if (context.customResolvers && obj && (obj.__typename || objId === 'ROOT_QUERY')) { var typename = obj.__typename || 'Query'; var type = context.customResolvers[typename]; if (type) { var resolver = type[fieldName]; if (resolver) { return resolver(obj, args); } } } if (!context.returnPartialData) { throw new Error("Can't find field " + storeKeyName + " on object (" + objId + ") " + JSON.stringify(obj, null, 2) + "."); } 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); } 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) {