How to use the apollo-link.Observable function in apollo-link

To help you get started, we’ve selected a few apollo-link examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github rse / apollo-client-ws / src / apollo-client-ws.js View on Github external
request (operation) {
        return new Observable((observer) => {
            this.emit("request", operation)
            this.log(1, "request: begin")
            /*  we here would have (but don't use):
                const { operationName, extensions, variables, query } = operation  */
            void (new Promise((resolve, reject) => {
                /*  optionally perform the deferred connect  */
                if (this._ws === null) {
                    this.log(2, "request: on-the-fly connect")
                    this.connect()
                        .then(() => resolve())
                        .catch((err) => reject(err))
                }
                else
                    resolve()
            }).then(() => {
                /*  await WebSocket ready-state OPEN  */
github apollographql / apollo-link / packages / apollo-link-persist / src / persistLink.ts View on Github external
public request(
    operation?: Operation,
    forward?: NextLink,
  ): Observable | null {
    const queryDocument = operation.query;
    const queryKey = getQueryDocumentKey(queryDocument);

    // If we are unable to find the query inside the query
    // map, we error on the returned observable and don't
    // proceed within the link stack.
    if (!this.queryMap[queryKey]) {
      return new Observable(observer => {
        observer.error(new Error('Could not find query inside query map.'));
      });
    }

    operation.query = null;
    operation.extensions = { queryId: this.queryMap[queryKey] };
    return forward(operation);
  }
}
github orbiting / republik-frontend / lib / apollo / appWorkerLink.js View on Github external
request(operation) {
    const id = uuid()

    return new Observable(observer => {
      // Sends operation to be processed in app "worker"
      this.postMessage(id, operation).then(response => {
        observer.next(response)
        observer.complete()
      })
    })
  }
}
github Canner / apollo-link-firebase / src / rtdb / subscriptionLink.ts View on Github external
const context: ResolverContext = {
      database: this.database,
      findType: fieldDirectives =>
        (fieldDirectives.rtdbSub && fieldDirectives.rtdbSub.type) ||
        (fieldDirectives.rtdbQuery && fieldDirectives.rtdbQuery.type),
      exportVal: {}
    };

    // Subscription operations must have exactly one root field.
    const onlyRootField: FieldNode = mainDefinition.selectionSet.selections[0] as FieldNode;

    // get directives
    const directives = getDirectiveInfoFromField(onlyRootField, operation.variables);
    const rtdbDirectives: SubDirectiveArgs = directives.rtdbSub as any;

    return new Observable(observer => {
      // we fetch the query outside the graphql-anywhere resolver
      // because subscription need to listen to event change
      const subQuery = createQuery({
        database: this.database,
        directives: rtdbDirectives
      });
      const {event} = rtdbDirectives;
      const callback = (snapshot: firebaseDatabase.DataSnapshot) => {
        const root: ResolverRoot = {rootSnapshot: snapshot};
        graphql(
          queryResolver,
          queryWithTypename,
          root,
          context,
          operation.variables
        )
github aerogear / offix / packages / sync / src / offline / OperationQueue.ts View on Github external
protected getObservable(entry: OperationQueueEntry) {
    return new Observable(observer => {
      entry.observer = observer;
      return () => this.dequeue(entry);
    });
  }
github DeltaCamp / apollo-link-ethereum / packages / apollo-link-ethereum-resolver-ethersjs / src / EthersResolver.ts View on Github external
_subscribeEvents (contractName, contractDirectives, fieldName, fieldArgs, fieldDirectives): Observable {
    return new Observable(observer => {
      this.actualProvider()
        .then(provider => {
          this._getContract(contractName, contractDirectives)
            .then(contract => {
              let options = fieldDirectives ? fieldDirectives.events : {}
              const filter = this._getFieldNameFilter(contract, contractName, fieldName, fieldArgs, options)
              subscriptionDebug(`Setup filter: `, filter)
              provider.on(filter, (log) => {
                const iface = this._getInterface(contractName)
                const event = {
                  log,
                  parsedLog: iface.parseLog(log)
                }
                subscriptionDebug(`filter ${contractName}.${fieldName} received `, filter, event)
                observer.next(event)
              })
github DeltaCamp / apollo-link-ethereum / packages / apollo-link-ethereum-resolver-web3js / src / Web3JSResolver.ts View on Github external
_subscribeEvents (contractName, contractDirectives, fieldName, fieldArgs, fieldDirectives): Observable {
    return new Observable(observer => {
      this._getContract(contractName, contractDirectives)
        .then(contract => {
          const eventFunction = contract.events[fieldName]
          if (!eventFunction) {
            observer.error(`Contract ${contractName} does not have an event called ${fieldName}`)
          } else {
            let options = fieldDirectives ? fieldDirectives.events : {}
            eventFunction(options)
              .on('data', (contractEvent) => {
                observer.next(contractEvent)
              })
              .on('changed', (contractEvent) => {
                observer.next({ changed: contractEvent })
              })
              .on('error', (error) => {
                observer.error(error)
github awslabs / aws-mobile-appsync-sdk-js / packages / aws-appsync-subscription-link / src / subscription-handshake-link.ts View on Github external
return new Observable(observer => {
                observer.error(new ApolloError({
                    errorMessage: 'Error during subscription handshake',
                    extraInfo: { errors },
                    graphQLErrors: errors
                }));

                return () => { };
            });
        }

        const newSubscriptionTopics = Object.keys(newSubscriptions).map(subKey => newSubscriptions[subKey].topic);
        const existingTopicsWithObserver = new Set(newSubscriptionTopics.filter(t => this.topicObservers.has(t)));
        const newTopics = new Set(newSubscriptionTopics.filter(t => !existingTopicsWithObserver.has(t)));

        return new Observable(observer => {
            existingTopicsWithObserver.forEach(t => {
                this.topicObservers.get(t).add(observer);
                const anObserver = Array.from(this.topicObservers.get(t)).find(() => true);

                const [clientId] = Array.from(this.clientObservers).find(([, { observers }]) => observers.has(anObserver));
                this.clientObservers.get(clientId).observers.add(observer);
            });

            const newTopicsConnectionInfo = mqttConnections
                .filter(c => c.topics.some(t => newTopics.has(t)))
                .map(({ topics, ...rest }) => ({
                    ...rest,
                    topics: topics.filter(t => newTopics.has(t))
                } as MqttConnectionInfo));

            this.connectNewClients(newTopicsConnectionInfo, observer, operation);
github Canner / canner / packages / canner-graphql-interface / src / link.ts View on Github external
if (fieldValue !== undefined) {
          return fieldValue;
        }
        return null;
      };

      const queryWithTypename = addTypenameToDocument(query);
      const connectors = multiConnectors
        ? mapValues(multiConnectors, connector => {
          return new DataLoaderConnector({keys: schemaKeys, connector});
        })
        : mapValues(schema, (value, key) => {
          return new DataLoaderConnector({keys: schemaKeys, connector: singleConnector});
        });

      return new Observable(observer => {
        graphql(
          graphqlResolver,
          queryWithTypename,
          {},
          {document: queryWithTypename, connectors},
          operation.variables
        )
        .then(data => {
          observer.next({ data });
          observer.complete();
        })
        .catch(err => {
          if (err.name === 'AbortError') {
            return;
          }
          if (err.result && err.result.errors) {
github molindo / react-apollo-network-status / src / ApolloLinkNetworkStatus.ts View on Github external
if (context.isNetworkStatusHandled !== true && !this.enableBubbling) {
      operation.setContext({isNetworkStatusHandled: true});
    } else {
      shouldDispatch = context.isNetworkStatusHandled !== true;
    }

    if (shouldDispatch) {
      this.dispatcher.dispatch({
        type: ActionTypes.REQUEST,
        payload: {operation}
      });
    }

    const subscriber = forward(operation);

    return new Observable(observer => {
      let isPending = true;

      const subscription = subscriber.subscribe({
        next: result => {
          isPending = false;

          if (shouldDispatch) {
            this.dispatcher.dispatch({
              type: ActionTypes.SUCCESS,
              payload: {operation, result}
            });
          }

          observer.next(result);
        },