All files / src ApolloClient.ts

86.9% Statements 73/84
75.93% Branches 41/54
88.24% Functions 15/17
86.49% Lines 64/74
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 3508x                       8x 8x   135x 135x 135x 135x 135x 135x 135x 135x 1x   135x 135x 135x 135x 135x     135x     8x   135x 8x 8x     8x 8x               135x   8x 71x 71x     71x   8x 56x 56x     56x 2x   56x   8x 58x 58x   8x 2x 2x   8x 10x   8x 18x   8x 26x   8x 15x   8x     8x 223x 223x 91x   132x           505x                             8x 1x   8x 69x 34x 34x   69x   8x                                                                                                                                                                                                                                                                                                                                                                                                                                                        
import { ApolloLink, FetchResult } from 'apollo-link-core';
import {
  Cache,
  DataProxy,
  DataProxyReadQueryOptions,
  DataProxyReadFragmentOptions,
  DataProxyWriteQueryOptions,
  DataProxyWriteFragmentOptions,
  DiffResult,
} from 'apollo-cache-core';
import { isProduction } from 'apollo-utilities';
 
import { QueryManager } from './core/QueryManager';
import { ApolloQueryResult } from './core/types';
import { ObservableQuery } from './core/ObservableQuery';
 
import { Observable } from './util/Observable';
 
import {
  WatchQueryOptions,
  SubscriptionOptions,
  MutationOptions,
} from './core/watchQueryOptions';
 
import { DataStore } from './data/store';
 
import { version } from './version';
 
let hasSuggestedDevtools = false;
 
/**
 * This is the primary Apollo Client class. It is used to send GraphQL documents (i.e. queries
 * and mutations) to a GraphQL spec-compliant server over a {@link NetworkInterface} instance,
 * receive results from the server and cache the results in a store. It also delivers updates
 * to GraphQL queries through {@link Observable} instances.
 */
export default class ApolloClient implements DataProxy {
  public link: ApolloLink;
  public store: DataStore;
  public queEryManager: QueryManager;
  public disableNetworkFetches: boolean;
  public version: string;
  public queryDeEduplication: boolean;
I
  private devToolsHookCb: Function;
  private proxy: DataProxy | undefined;
  private ssrMode: boolean;
 
  /**
   * Constructs an instance of {@link ApolloClient}.
   *
   * @param link The {@link ApolloLink} over which GraphQL documents will be resolved into a response.
   *
   * @param initialState The initial state assigned to the store.
   *
   * @paIram initialCache The initial cache to use in the data store.
   *
   * @param ssrMode Determines whether this is being run in Server Side Rendering (SSR) mode.
   *
   * @param ssrForceFetchDelay Determines the time interval before we force fetch queries for a
   * server side render.
   *
   *I
   * @param queryDeduplication If set to false, a query will still be sent to the server even if a query
   * with identical parameters (query, variables, operationName) is already in flight.
   *
   * @param fragmentMatcher A function to use for matching fragment conditions in GraphQL documents
   */
 
  constructor(options: {
    link: ApolloLink;
    cache: Cache;
    ssrMode?: boolean;
    ssrForceFetchDelay?: number;
    connectToDevTools?: boolean;
    queryDeduplication?: boolean;
  }) {
    const {
      link,
      cache,
      ssrMode = false,
      ssrForceFetchDelay = 0,
      connectToDevTools,
      queryDeduplication = true,
    } = options;
 
    this.link = link;
    this.store = new DataStore(cache);
    this.disableNetworkFetches = ssrMode || ssrForceFetchDelay > 0;
    this.queryDeduplication = queryDeduplication;
    this.ssrMode = ssrMode;

    if (ssrForceFetchDelay) {
      setTimeout(
        () => (this.disableNetworkFetches = false),
        ssrForceFetchDelay,
      );
    }
 
    this.watchQuery = this.watchQuery.bind(this);
    this.query = this.query.bind(this);
    this.mutate = this.mutate.bind(this);
    this.resetStore = this.resetStore.bind(this);
 
    // Attach thIe client instance to window to let us be found by chrome devtools, but only in
    // development mode
    const defaultConnectToDevTools =
      !isProduction() &&
      typeof window !== 'undefined' &&
      !(window as any).__APOLLO_CLIENT__;
 
    if (
      typeof connectToDevTools === 'undefined'
        ? defaultConnectToDevTools
        : connectToDevTools
    ) {
      (window as any).__APOLLO_CLIENT__ = this;
    }
 
    /**
     * Suggest installing the devtools for developers who don't have them
     */
    if (!hasSuggestedDevtools && !isProduction()) {
      hasSuggestedDevtools = true;
      if (
        typeof window !== 'undefined' &&
        window.document &&
        window.top === window.self
      ) {
        // First check if devtools is not installed
        if (
          typeof (window as any).__APOLLO_DEVTOOLS_GLOBAL_HOOK__ === 'undefined'
        ) {
          // Only for Chrome
          if (navigator.userAgent.indexOf('Chrome') > -1) {
            // tslint:disable-next-line
            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;
  }
  /**
   * This watches the results of the query according to the options specified and
   * returns an {@link ObservableQuery}. We can subscribe to this {@link ObservableQuery} and
   * receive updated results through a GraphQL observer.
   * <p /><p />
   * Note that this method is not an implementation of GraphQL subscriptions. Rather,
   * it uses Apollo's store in order to reactively deliver updates to your query results.
   * <p /><p />
   * For example, suppose you call watchQuery on a GraphQL query that fetches an person's
   * first name and last name and this person has a particular object identifer, provided by
   * dataIdFromObject. Later, a different query fetches that same person's
   * first and last name and his/her first name has now changed. Then, any observers associated
   * with the results of the first query will be updated with a new result object.
   * <p /><p />
   * See [here](https://medium.com/apollo-stack/the-concepts-of-graphql-bc68bd819be3#.3mb0cbcmc) for
   * a description of store reactivity.
   *
   */
  public watchQuery<T>(options: WatchQueryOptions): ObservableQuery<T> {
    this.initQueryManager();
 
    // XXX Overwriting options is probably not the best way to do this long term...
    if (this.disableNetworkFetches && options.fetchPolicy === 'network-only') {
      options = {
        ...options,
        fetchPolicy: 'cache-first',
      } as WatchQueryOptions;
    }
 
    return this.queryManager.watchQuery<T>(options);
  }
 
  /**
   * This resolves a single query according to the options specified and returns a
   * {@link Promise} which is either resolved with the resulting data or rejected
   * with an error.
   *
   * @param options An object of type {@link WatchQueryOptions} that allows us to describe
   * how this query should be treated e.g. whether it is a polling query, whether it should hit the
   * server at all or just resolve from the cache, etc.
   */
  public query<T>(options: WatchQueryOptions): Promise<ApolloQueryResult<T>> {
    this.initQueryManager();
 
    if (options.fetchPolicy === 'cache-and-network') {
      throw new Error(
        'cache-and-network fetchPolicy can only be used with watchQuery',
      );
    }
 
    // XXX Overwriting options is probably not the best way to do this long term...
    if (this.disableNetworkFetches && options.fetchPolicy === 'network-only') {
      options = {
        ...options,
        fetchPolicy: 'cache-first',
      } as WatchQueryOptions;
    }
 
    return this.queryManager.query<T>(options);
  }
 
  /**
   * This resolves a single mutation according to the options specified and returns a
   * {@link Promise} which is either resolved with the resulting data or rejected with an
   * error.
   *
   * It takes options as an object with the following keys and values:
   */
  public mutate<T>(options: MutationOptions<T>): Promise<FetchResult<T>> {
    this.initQueryManager();
 
    return this.queryManager.mutate<T>(options);
  }
 
  /**
   * This subscribes to a graphql subscription according to the options specified and returns an
   * {@link Observable} which either emits received data or an error.
   */
  public subscribe(options: SubscriptionOptions): Observable<any> {
    this.initQueryManager();
 
    return this.queryManager.startGraphQLSubscription(options);
  }
 
  /**
   * Tries to read some data from the store in the shape of the provided
   * GraphQL query without making a network request. This method will start at
   * the root query. To start at a specific id returned by `dataIdFromObject`
   * use `readFragment`.
   */
  public readQuery<T>(options: DataProxyReadQueryOptions): DiffResult<T> {
    return this.initProxy().readQuery<T>(options);
  }
 
  /**
   * Tries to read some data from the store in the shape of the provided
   * GraphQL fragment without making a network request. This method will read a
   * GraphQL fragment from any arbitrary id that is currently cached, unlike
   * `readQuery` which will only read from the root query.
   *
   * You must pass in a GraphQL document with a single fragment or a document
   * with multiple fragments that represent what you are reading. If you pass
   * in a document with multiple fragments then you must also specify a
   * `fragmentName`.
   */
  public readFragment<T>(
    options: DataProxyReadFragmentOptions,
  ): DiffResult<T> | null {
    return this.initProxy().readFragment<T>(options);
  }
 
  /**
   * Writes some data in the shape of the provided GraphQL query directly to
   * the store. This method will start at the root query. To start at a a
   * specific id returned by `dataIdFromObject` then use `writeFragment`.
   */
  public writeQuery(options: DataProxyWriteQueryOptions): void {
    return this.initProxy().writeQuery(options);
  }
 
  /**
   * Writes some data in the shape of the provided GraphQL fragment directly to
   * the store. This method will write to a GraphQL fragment from any arbitrary
   * id that is currently cached, unlike `writeQuery` which will only write
   * from the root query.
   *
   * You must pass in a GraphQL document with a single fragment or a document
   * with multiple fragments that represent what you are writing. If you pass
   * in a document with multiple fragments then you must also specify a
   * `fragmentName`.
   */
  public writeFragment(options: DataProxyWriteFragmentOptions): void {
    return this.initProxy().writeFragment(options);
  }
 
  public __actionHookForDevTools(cb: Function) {
    this.devToolsHookCb = cb;
  }
 
  /**
   * This initializes the query manager that tracks queries and the cache
   */
  public initQueryManager() {
    if (this.queryManager) {
      return;
    }
 
    this.queryManager = new QueryManager({
      link: this.link,
      store: this.store,
      queryDeduplication: this.queryDeduplication,
      ssrMode: this.ssrMode,
      onBroadcast: () => {
        if (this.devToolsHookCb) {
          this.devToolsHookCb({
            action: {},
            state: {
              queries: this.queryManager.queryStore.getStore(),
              mutations: this.queryManager.mutationStore.getStore(),
            },
            dataWithOptimisticResults: this.queryManager.dataStore
              .getCache()
              .getOptimisticData(),
          });
        }
      },
    });
  }
 
  /**
   * Resets your entire store by clearing out your cache and then re-executing
   * all of your active queries. This makes it so that you may guarantee that
   * there is no data left in your store from a time before you called this
   * method.
   *
   * `resetStore()` is useful when your user just logged out. You’ve removed the
   * user session, and you now want to make sure that any references to data you
   * might have fetched while the user session was active is gone.
   *
   * It is important to remember that `resetStore()` *will* refetch any active
   * queries. This means that any components that might be mounted will execute
   * their queries again using your network interface. If you do not want to
   * re-execute any queries then you should make sure to stop watching any
   * active queries.
   */
  public resetStore(): Promise<ApolloQueryResult<any>[]> | null {
    return this.queryManager ? this.queryManager.resetStore() : null;
  }
 
  /**
   * Initializes a data proxy for this client instance if one does not already
   * exist and returns either a previously initialized proxy instance or the
   * newly initialized instance.
   */
  private initProxy(): DataProxy {
    if (!this.proxy) {
      this.initQueryManager();
      this.proxy = this.queryManager.dataStore.getCache();
    }
    return this.proxy;
  }
}