@apollo/client/core#FetchResult TypeScript Examples

The following examples show how to use @apollo/client/core#FetchResult. 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: SentryLink.ts    From apollo-link-sentry with MIT License 5 votes vote down vote up
function severityForResult(result: FetchResult): Severity {
  return result.errors && result.errors.length > 0
    ? Severity.Error
    : Severity.Info;
}
Example #2
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 #3
Source File: apollo-link.test.ts    From graphql-mesh with MIT License 5 votes vote down vote up
describe('GraphApolloLink', () => {
  let client: ApolloClient<any>;
  let mesh: MeshInstance;
  beforeEach(async () => {
    mesh = await getTestMesh();
    client = new ApolloClient({
      link: new MeshApolloLink(mesh),
      cache: new InMemoryCache(),
    });
  });
  afterEach(() => {
    mesh?.destroy();
  });
  it('should handle queries correctly', async () => {
    const result = await client.query({
      query: parse(/* GraphQL */ `
        query Greetings {
          greetings
        }
      `),
    });
    expect(result.error).toBeUndefined();
    expect(result.errors?.length).toBeFalsy();
    expect(result.data).toEqual({
      greetings: 'This is the `greetings` field of the root `Query` type',
    });
  });
  it('should handle subscriptions correctly', async () => {
    const observable = client.subscribe({
      query: parse(/* GraphQL */ `
        subscription Time {
          time
        }
      `),
    });
    const asyncIterable =
      observableToAsyncIterable<FetchResult<any, Record<string, any>, Record<string, any>>>(observable);
    let i = 0;
    for await (const result of asyncIterable) {
      i++;
      if (i === 2) {
        break;
      }
      expect(result.errors?.length).toBeFalsy();
      const date = new Date(result?.data?.time);
      expect(date.getFullYear()).toBe(new Date().getFullYear());
    }
    expect(i).toBe(2);
  });
});
Example #4
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();
      };
    });
  }