@apollo/client/core#ObservableQuery TypeScript Examples

The following examples show how to use @apollo/client/core#ObservableQuery. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApolloExtensionsClient.ts    From apollo-cache-policies with Apache License 2.0 6 votes vote down vote up
// Watches the data in the cache similarly to watchQuery for a given fragment.
  watchFragment(
    options: WatchFragmentOptions,
  ): ObservableQuery {
    const fieldName = generateFragmentFieldName();
    const query = buildWatchFragmentQuery({
      ...options,
      fieldName,
      policies: this.policies,
    });

    return this.watchQueryForField(query, fieldName);
  }
Example #2
Source File: ApolloExtensionsClient.ts    From apollo-cache-policies with Apache License 2.0 5 votes vote down vote up
// Watches the data in the cache similarly to watchQuery and additionally extracts the given fieldName from the watch query
  // subscription and returns a subscription that emits that field data.
  private watchQueryForField(query: DocumentNode, fieldName: string): ObservableQuery {
    const obsQuery = this.watchQuery({
      fetchPolicy: 'cache-only',
      query: query,
    });

    const subscribe = obsQuery.subscribe.bind(obsQuery);

    obsQuery.subscribe = (observer, ...rest) => {
      // This check is modeled after the Zen Observable observer check:
      // https://github.com/zenparsing/zen-observable/blob/master/src/Observable.js#L211
      if (typeof observer !== 'object') {
        observer = {
          next: observer,
          error: rest[0] as (error: any) => void,
          complete: rest[1] as () => void,
        };
      }

      const observerNext = observer.next;

      // The observer maps the value emitted from the observable to the data at the
      // given field name.
      observer.next = (value: Record<string, any>) => {
        if (observerNext) {
          observerNext(value?.data?.[fieldName]);
        }
      }

      const subscription = subscribe(observer);
      const unsubscribe = subscription.unsubscribe.bind(subscription);

      subscription.unsubscribe = () => {
        // @ts-ignore typePolicies is private. Delete the field name from the type policies
        // after the subscription has been cleaned up.
        delete this.cache.policies.typePolicies.Query.fields[fieldName];
        unsubscribe();
      }

      return subscription;
    }

    return obsQuery;
  }