UNPKG

12.4 kBJavaScriptView Raw
1var __assign = (this && this.__assign) || Object.assign || function(t) {
2 for (var s, i = 1, n = arguments.length; i < n; i++) {
3 s = arguments[i];
4 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
5 t[p] = s[p];
6 }
7 return t;
8};
9import { createNetworkInterface, } from './transport/networkInterface';
10import { execute, ApolloLink } from 'apollo-link-core';
11import { HeuristicFragmentMatcher, } from './data/fragmentMatcher';
12import { createApolloStore, createApolloReducer, } from './store';
13import { QueryManager } from './core/QueryManager';
14import { isProduction } from './util/environment';
15import { getStoreKeyName } from './data/storeUtils';
16import { ReduxDataProxy, } from './data/proxy';
17import { version } from './version';
18var DEFAULT_REDUX_ROOT_KEY = 'apollo';
19function defaultReduxRootSelector(state) {
20 return state[DEFAULT_REDUX_ROOT_KEY];
21}
22function defaultDataIdFromObject(result) {
23 if (result.__typename) {
24 if (result.id !== undefined) {
25 return result.__typename + ":" + result.id;
26 }
27 if (result._id !== undefined) {
28 return result.__typename + ":" + result._id;
29 }
30 }
31 return null;
32}
33var hasSuggestedDevtools = false;
34var ApolloClient = (function () {
35 function ApolloClient(options) {
36 if (options === void 0) { options = {}; }
37 var _this = this;
38 this.middleware = function () {
39 return function (store) {
40 _this.setStore(store);
41 return function (next) { return function (action) {
42 var previousApolloState = _this.queryManager.selectApolloState(store);
43 var returnValue = next(action);
44 var newApolloState = _this.queryManager.selectApolloState(store);
45 if (newApolloState !== previousApolloState) {
46 _this.queryManager.broadcastNewStore(store.getState());
47 }
48 if (_this.devToolsHookCb) {
49 _this.devToolsHookCb({
50 action: action,
51 state: {
52 queries: _this.queryManager.queryStore.getStore(),
53 mutations: _this.queryManager.mutationStore.getStore(),
54 },
55 dataWithOptimisticResults: _this.queryManager.getDataWithOptimisticResults(),
56 });
57 }
58 return returnValue;
59 }; };
60 };
61 };
62 var dataIdFromObject = options.dataIdFromObject;
63 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;
64 if (typeof reduxRootSelector === 'function') {
65 this.reduxRootSelector = reduxRootSelector;
66 }
67 else if (typeof reduxRootSelector !== 'undefined') {
68 throw new Error('"reduxRootSelector" must be a function.');
69 }
70 if (typeof fragmentMatcher === 'undefined') {
71 this.fragmentMatcher = new HeuristicFragmentMatcher();
72 }
73 else {
74 this.fragmentMatcher = fragmentMatcher;
75 }
76 var createQuery = function (getResult) {
77 var resolved = false;
78 return function (request) {
79 return new Promise(function (resolve, reject) {
80 var subscription = getResult(request).subscribe({
81 next: function (data) {
82 if (!resolved) {
83 resolve(data);
84 resolved = true;
85 }
86 else {
87 console.warn('Apollo Client does not support multiple results from an Observable');
88 }
89 },
90 error: reject,
91 complete: function () { return subscription.unsubscribe(); },
92 });
93 });
94 };
95 };
96 if (networkInterface instanceof ApolloLink) {
97 this.networkInterface = {
98 query: createQuery(function (request) {
99 return execute(networkInterface, request);
100 }),
101 };
102 }
103 else if (networkInterface &&
104 typeof networkInterface.request ===
105 'function') {
106 console.warn("The Observable Network interface will be deprecated");
107 this.networkInterface = __assign({}, networkInterface, { query: createQuery(networkInterface.request) });
108 }
109 else {
110 this.networkInterface = networkInterface
111 ? networkInterface
112 : createNetworkInterface({ uri: '/graphql' });
113 }
114 this.initialState = initialState ? initialState : {};
115 this.addTypename = addTypename;
116 this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0;
117 this.dataId = dataIdFromObject =
118 dataIdFromObject || defaultDataIdFromObject;
119 this.dataIdFromObject = this.dataId;
120 this.fieldWithArgs = getStoreKeyName;
121 this.queryDeduplication = queryDeduplication;
122 this.ssrMode = ssrMode;
123 if (ssrForceFetchDelay) {
124 setTimeout(function () { return (_this.disableNetworkFetches = false); }, ssrForceFetchDelay);
125 }
126 this.reducerConfig = {
127 dataIdFromObject: dataIdFromObject,
128 customResolvers: customResolvers,
129 addTypename: addTypename,
130 fragmentMatcher: this.fragmentMatcher.match,
131 };
132 this.watchQuery = this.watchQuery.bind(this);
133 this.query = this.query.bind(this);
134 this.mutate = this.mutate.bind(this);
135 this.setStore = this.setStore.bind(this);
136 this.resetStore = this.resetStore.bind(this);
137 var defaultConnectToDevTools = !isProduction() &&
138 typeof window !== 'undefined' &&
139 !window.__APOLLO_CLIENT__;
140 if (typeof connectToDevTools === 'undefined'
141 ? defaultConnectToDevTools
142 : connectToDevTools) {
143 window.__APOLLO_CLIENT__ = this;
144 }
145 if (!hasSuggestedDevtools && !isProduction()) {
146 hasSuggestedDevtools = true;
147 if (typeof window !== 'undefined' &&
148 window.document &&
149 window.top === window.self) {
150 if (typeof window.__APOLLO_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
151 if (navigator.userAgent.indexOf('Chrome') > -1) {
152 console.debug('Download the Apollo DevTools ' +
153 'for a better development experience: ' +
154 'https://chrome.google.com/webstore/detail/apollo-client-developer-t/jdkknkkbebbapilgoeccciglkfbmbnfm');
155 }
156 }
157 }
158 }
159 this.version = version;
160 }
161 ApolloClient.prototype.watchQuery = function (options) {
162 this.initStore();
163 if (this.disableNetworkFetches && options.fetchPolicy === 'network-only') {
164 options = __assign({}, options, { fetchPolicy: 'cache-first' });
165 }
166 return this.queryManager.watchQuery(options);
167 };
168 ApolloClient.prototype.query = function (options) {
169 this.initStore();
170 if (options.fetchPolicy === 'cache-and-network') {
171 throw new Error('cache-and-network fetchPolicy can only be used with watchQuery');
172 }
173 if (this.disableNetworkFetches && options.fetchPolicy === 'network-only') {
174 options = __assign({}, options, { fetchPolicy: 'cache-first' });
175 }
176 return this.queryManager.query(options);
177 };
178 ApolloClient.prototype.mutate = function (options) {
179 this.initStore();
180 return this.queryManager.mutate(options);
181 };
182 ApolloClient.prototype.subscribe = function (options) {
183 this.initStore();
184 return this.queryManager.startGraphQLSubscription(options);
185 };
186 ApolloClient.prototype.readQuery = function (options) {
187 return this.initProxy().readQuery(options);
188 };
189 ApolloClient.prototype.readFragment = function (options) {
190 return this.initProxy().readFragment(options);
191 };
192 ApolloClient.prototype.writeQuery = function (options) {
193 return this.initProxy().writeQuery(options);
194 };
195 ApolloClient.prototype.writeFragment = function (options) {
196 return this.initProxy().writeFragment(options);
197 };
198 ApolloClient.prototype.reducer = function () {
199 return createApolloReducer(this.reducerConfig);
200 };
201 ApolloClient.prototype.__actionHookForDevTools = function (cb) {
202 this.devToolsHookCb = cb;
203 };
204 ApolloClient.prototype.initStore = function () {
205 var _this = this;
206 if (this.store) {
207 return;
208 }
209 if (this.reduxRootSelector) {
210 throw new Error('Cannot initialize the store because "reduxRootSelector" is provided. ' +
211 'reduxRootSelector should only be used when the store is created outside of the client. ' +
212 'This may lead to unexpected results when querying the store internally. ' +
213 "Please remove that option from ApolloClient constructor.");
214 }
215 this.setStore(createApolloStore({
216 reduxRootKey: DEFAULT_REDUX_ROOT_KEY,
217 initialState: this.initialState,
218 config: this.reducerConfig,
219 logger: function (store) { return function (next) { return function (action) {
220 var result = next(action);
221 if (_this.devToolsHookCb) {
222 _this.devToolsHookCb({
223 action: action,
224 state: {
225 queries: _this.queryManager.queryStore.getStore(),
226 mutations: _this.queryManager.mutationStore.getStore(),
227 },
228 dataWithOptimisticResults: _this.queryManager.getDataWithOptimisticResults(),
229 });
230 }
231 return result;
232 }; }; },
233 }));
234 };
235 ApolloClient.prototype.resetStore = function () {
236 return this.queryManager ? this.queryManager.resetStore() : null;
237 };
238 ApolloClient.prototype.getInitialState = function () {
239 this.initStore();
240 return this.queryManager.getInitialState();
241 };
242 ApolloClient.prototype.setStore = function (store) {
243 var reduxRootSelector;
244 if (this.reduxRootSelector) {
245 reduxRootSelector = this.reduxRootSelector;
246 }
247 else {
248 reduxRootSelector = defaultReduxRootSelector;
249 }
250 if (typeof reduxRootSelector(store.getState()) === 'undefined') {
251 throw new Error('Existing store does not use apolloReducer. Please make sure the store ' +
252 'is properly configured and "reduxRootSelector" is correctly specified.');
253 }
254 this.store = store;
255 this.queryManager = new QueryManager({
256 networkInterface: this.networkInterface,
257 reduxRootSelector: reduxRootSelector,
258 store: store,
259 addTypename: this.addTypename,
260 reducerConfig: this.reducerConfig,
261 queryDeduplication: this.queryDeduplication,
262 fragmentMatcher: this.fragmentMatcher,
263 ssrMode: this.ssrMode,
264 });
265 };
266 ApolloClient.prototype.initProxy = function () {
267 if (!this.proxy) {
268 this.initStore();
269 this.proxy = new ReduxDataProxy(this.store, this.reduxRootSelector || defaultReduxRootSelector, this.fragmentMatcher, this.reducerConfig);
270 }
271 return this.proxy;
272 };
273 return ApolloClient;
274}());
275export default ApolloClient;
276//# sourceMappingURL=ApolloClient.js.map
\No newline at end of file