@apollo/client/core#Operation TypeScript Examples

The following examples show how to use @apollo/client/core#Operation. 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: operation.ts    From apollo-link-sentry with MIT License 6 votes vote down vote up
export function extractDefinition(
  operation: Operation,
): OperationDefinitionNode {
  // We know we always have a single definition, because Apollo validates this before we get here.
  // With more then one query defined, an error like this is thrown and the query is never sent:
  // "react-apollo only supports a query, subscription, or a mutation per HOC. [object Object] had 2 queries, 0 subscriptions and 0 mutations. You can use 'compose' to join multiple operation types to a component"
  return operation.query.definitions.find(
    (q) => q.kind === 'OperationDefinition',
  ) as OperationDefinitionNode;
}
Example #2
Source File: sentry.ts    From apollo-link-sentry with MIT License 6 votes vote down vote up
export function setTransaction(operation: Operation): void {
  const definition = extractDefinition(operation);
  const name = definition.name;

  if (name) {
    configureScope((scope: Scope) => {
      scope.setTransactionName(name.value);
    });
  }
}
Example #3
Source File: sentry.ts    From apollo-link-sentry with MIT License 6 votes vote down vote up
export function setFingerprint(operation: Operation): void {
  const definition = extractDefinition(operation);
  const name = definition.name;

  if (name) {
    configureScope((scope: Scope) => {
      scope.setFingerprint([DEFAULT_FINGERPRINT, name.value]);
    });
  }
}
Example #4
Source File: sentry.ts    From apollo-link-sentry with MIT License 6 votes vote down vote up
export function attachBreadcrumbToSentry(
  operation: Operation,
  breadcrumb: GraphQLBreadcrumb,
  options: FullOptions,
): void {
  const transformed: Breadcrumb =
    options.attachBreadcrumbs &&
    typeof options.attachBreadcrumbs.transform === 'function'
      ? options.attachBreadcrumbs.transform(breadcrumb, operation)
      : breadcrumb;

  transformed.data = stringifyObjectKeys(
    transformed.data as Record<string, unknown>,
  );

  addBreadcrumb(transformed);
}
Example #5
Source File: operation.test.ts    From apollo-link-sentry with MIT License 6 votes vote down vote up
export function makeOperation(overwrites: Partial<Operation> = {}): Operation {
  return {
    query: parse(`query Foo { foo }`),
    operationName: 'Foo',
    variables: {},
    extensions: {},
    getContext: () => ({}),
    setContext: (context) => context,

    ...overwrites,
  };
}
Example #6
Source File: breadcrumb.ts    From apollo-link-sentry with MIT License 5 votes vote down vote up
export function makeBreadcrumb(
  operation: Operation,
  options: FullOptions,
): GraphQLBreadcrumb {
  // We validated this is set before calling this function
  const attachBreadcrumbs =
    options.attachBreadcrumbs as AttachBreadcrumbsOptions;

  const definition = extractDefinition(operation);

  const data: BreadcrumbData = {};

  const uri = options.uri;
  if (uri) {
    data.url = uri;
  }

  const operationName = definition.name?.value;
  if (operationName) {
    data.operationName = operationName;
  }

  if (attachBreadcrumbs.includeQuery) {
    data.query =
      // The document might have been parsed with `noLocation: true`
      definition.loc?.source?.body ?? print(definition);
  }

  if (attachBreadcrumbs.includeVariables) {
    data.variables = operation.variables;
  }

  if (attachBreadcrumbs.includeCache) {
    data.cache =
      (operation.getContext().cache?.data?.data as Record<string, unknown>) ??
      undefined;
  }

  const contextKeys = attachBreadcrumbs.includeContext;
  if (contextKeys) {
    data.context = extractKeys(operation.getContext(), contextKeys);
  }

  return {
    type: 'http',
    category: `graphql.${definition.operation}`,
    data,
  };
}
Example #7
Source File: index.ts    From graphql-mesh with MIT License 5 votes vote down vote up
function createMeshApolloRequestHandler(options: MeshApolloRequestHandlerOptions): RequestHandler {
  return function meshApolloRequestHandler(operation: Operation): Observable<FetchResult> {
    const operationAst = getOperationAST(operation.query, operation.operationName);
    if (!operationAst) {
      throw new Error('GraphQL operation not found');
    }
    const operationFn = operationAst.operation === 'subscription' ? options.subscribe : options.execute;
    return new Observable(observer => {
      Promise.resolve()
        .then(async () => {
          const results = await operationFn(
            operation.query,
            operation.variables,
            operation.getContext(),
            ROOT_VALUE,
            operation.operationName
          );
          if (isAsyncIterable(results)) {
            for await (const result of results) {
              if (observer.closed) {
                return;
              }
              observer.next(result);
            }
            observer.complete();
          } else {
            if (!observer.closed) {
              observer.next(results);
              observer.complete();
            }
          }
        })
        .catch(error => {
          if (!observer.closed) {
            observer.error(error);
          }
        });
    });
  };
}
Example #8
Source File: SentryLink.ts    From apollo-link-sentry with MIT License 4 votes vote down vote up
request(
    operation: Operation,
    forward: NextLink,
  ): Observable<FetchResult> | null {
    const options = this.options;

    if (!(options.shouldHandleOperation?.(operation) ?? true)) {
      return forward(operation);
    }

    if (options.setTransaction) {
      setTransaction(operation);
    }

    if (options.setFingerprint) {
      setFingerprint(operation);
    }

    const attachBreadcrumbs = options.attachBreadcrumbs;
    const breadcrumb = attachBreadcrumbs
      ? makeBreadcrumb(operation, options)
      : undefined;

    // While this could be done more simplistically by simply subscribing,
    // wrapping the observer in our own observer ensures we get the results
    // before they are passed along to other observers. This guarantees we
    // get to run our instrumentation before others observers potentially
    // throw and thus flush the results to Sentry.
    return new Observable<FetchResult>((originalObserver) => {
      const subscription = forward(operation).subscribe({
        next: (result) => {
          if (attachBreadcrumbs) {
            // We must have a breadcrumb if attachBreadcrumbs was set
            (breadcrumb as GraphQLBreadcrumb).level = severityForResult(result);

            if (attachBreadcrumbs.includeFetchResult) {
              // We must have a breadcrumb if attachBreadcrumbs was set
              (breadcrumb as GraphQLBreadcrumb).data.fetchResult = result;
            }

            if (
              attachBreadcrumbs.includeError &&
              result.errors &&
              result.errors.length > 0
            ) {
              // We must have a breadcrumb if attachBreadcrumbs was set
              (breadcrumb as GraphQLBreadcrumb).data.error = new ApolloError({
                graphQLErrors: result.errors,
              });
            }
          }

          originalObserver.next(result);
        },
        complete: () => {
          if (attachBreadcrumbs) {
            attachBreadcrumbToSentry(
              operation,
              // We must have a breadcrumb if attachBreadcrumbs was set
              breadcrumb as GraphQLBreadcrumb,
              options,
            );
          }

          originalObserver.complete();
        },
        error: (error) => {
          if (attachBreadcrumbs) {
            // We must have a breadcrumb if attachBreadcrumbs was set
            (breadcrumb as GraphQLBreadcrumb).level = Severity.Error;

            let scrubbedError;
            if (isServerError(error)) {
              const { result, response, ...rest } = error;
              scrubbedError = rest;

              if (attachBreadcrumbs.includeFetchResult) {
                // We must have a breadcrumb if attachBreadcrumbs was set
                (breadcrumb as GraphQLBreadcrumb).data.fetchResult = result;
              }
            } else {
              scrubbedError = error;
            }

            if (attachBreadcrumbs.includeError) {
              // We must have a breadcrumb if attachBreadcrumbs was set
              (breadcrumb as GraphQLBreadcrumb).data.error = scrubbedError;
            }

            attachBreadcrumbToSentry(
              operation,
              // We must have a breadcrumb if attachBreadcrumbs was set
              breadcrumb as GraphQLBreadcrumb,
              options,
            );
          }

          originalObserver.error(error);
        },
      });

      return () => {
        subscription.unsubscribe();
      };
    });
  }