How to use apollo-link - 10 common examples

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 apollographql / apollo-client / packages / apollo-client / src / __tests__ / client.ts View on Github external
it('creates query manager lazily', () => {
    const client = new ApolloClient({
      link: ApolloLink.empty(),
      cache: new InMemoryCache(),
    });

    expect(client.queryManager).toBeUndefined();

    // We only create the query manager on the first query
    client.initQueryManager();
    expect(client.queryManager).toBeDefined();
    expect(client.cache).toBeDefined();
  });
github apollographql / apollo-link / packages / apollo-link-retry / src / __tests__ / retryLink.ts View on Github external
it('calls unsubscribe on the appropriate downstream observable', async () => {
    const retry = new RetryLink({
      delay: { initial: 1 },
      attempts: { max: 2 },
    });
    const data = { data: { hello: 'world' } };
    const unsubscribeStub = jest.fn();

    const firstTry = fromError(standardError);
    // Hold the test hostage until we're hit
    let secondTry;
    const untilSecondTry = new Promise(resolve => {
      secondTry = {
        subscribe(observer) {
          resolve(); // Release hold on test.

          Promise.resolve().then(() => {
            observer.next(data);
            observer.complete();
          });
          return { unsubscribe: unsubscribeStub };
        },
      };
    });
github apollographql / apollo-link / packages / apollo-link-batch / src / __tests__ / batchLink.ts View on Github external
new Observable(observer => {
          observer.next([{ data }, { data: data2 }, { data }]);
          setTimeout(observer.complete.bind(observer));
        }),
    });
    const query = gql`
      query {
        author {
          firstName
          lastName
        }
      }
    `;
    const operation: Operation = createOperation({}, { query });
    const operation2: Operation = createOperation({}, { query });
    const operation3: Operation = createOperation({}, { query });

    batcher.enqueueRequest({ operation }).subscribe({});
    batcher.enqueueRequest({ operation: operation2 }).subscribe({});
    try {
      expect(batcher.queuedRequests.get('').length).toBe(2);
    } catch (e) {
      done.fail(e);
    }

    setTimeout(() => {
      // The batch shouldn't be fired yet, so we can add one more request.
      batcher.enqueueRequest({ operation: operation3 }).subscribe({});
      try {
        expect(batcher.queuedRequests.get('').length).toBe(3);
      } catch (e) {
        done.fail(e);
github apollographql / apollo-link / packages / apollo-link-batch / src / __tests__ / batchLink.ts View on Github external
batchHandler: () =>
        new Observable(observer => {
          observer.next([{ data }, { data: data2 }, { data }]);
          setTimeout(observer.complete.bind(observer));
        }),
    });
    const query = gql`
      query {
        author {
          firstName
          lastName
        }
      }
    `;
    const operation: Operation = createOperation({}, { query });
    const operation2: Operation = createOperation({}, { query });
    const operation3: Operation = createOperation({}, { query });

    batcher.enqueueRequest({ operation }).subscribe({});
    batcher.enqueueRequest({ operation: operation2 }).subscribe({});
    try {
      expect(batcher.queuedRequests.get('').length).toBe(2);
    } catch (e) {
      done.fail(e);
    }

    setTimeout(() => {
      // The batch shouldn't be fired yet, so we can add one more request.
      batcher.enqueueRequest({ operation: operation3 }).subscribe({});
      try {
        expect(batcher.queuedRequests.get('').length).toBe(3);
      } catch (e) {
github arkhn / pyrog / client / src / app.tsx View on Github external
}
  }
});

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.map(({ message, locations, path }) =>
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
      )
    );

  if (networkError) console.log(`[Network error]: ${networkError}`);
});

const coreLink = split(
  // Split based on operation type
  ({ query }) => {
    const definition = getMainDefinition(query);
    return (
      definition.kind === "OperationDefinition" &&
      definition.operation === "subscription"
    );
  },
  wsLink,
  httpLinkAuth
);

// Aggregate all links
const links = [];
if (process.env.NODE_ENV === "development") {
  links.push(errorLink);
github cdmbase / fullstack-pro / servers / frontend-server / src / config / apollo-client.ts View on Github external
lazy: true,
            connectionParams,
            connectionCallback: async (error) => {
                if (error) {
                    logger.trace('[connectionCallback error] %j', error);
                    // error.message has to match what the server returns.
                    if ((error as any).message === 'TokenExpired') {
                        console.log('onTokenError about to call');
                        // Reset the WS connection for it to carry the new JWT.
                        (wsLink as any).subscriptionClient.close(false, false);
                    }
                }
            },
        },
    });
    link = ApolloLink.split(
        ({ query, operationName }) => {
            if (operationName.endsWith('_WS')) {
                return true;
            } else {
                const operationAST = getOperationAST(query as any, operationName);
                return !!operationAST && operationAST.operation === 'subscription';
            }
        },
        wsLink,
        new HttpLink({
            uri: PUBLIC_SETTINGS.GRAPHQL_URL,
        }),
    );
} else {
    link = new BatchHttpLink({ uri: PUBLIC_SETTINGS.LOCAL_GRAPHQL_URL });
}
github sysgears / apollo-universal-starter-kit / src / client / app / Main.jsx View on Github external
for (const afterware of modules.afterwares) {
      afterware(response, options);
    }
  } catch (e) {
    console.error(e);
  }
  next();
});

let connectionParams = {};
for (const connectionParam of modules.connectionParams) {
  Object.assign(connectionParams, connectionParam());
}

const wsUri = apiUri.replace(/^http/, 'ws');
let link = ApolloLink.split(
  operation => {
    const operationAST = getOperationAST(operation.query, operation.operationName);
    return !!operationAST && operationAST.operation === 'subscription';
  },
  new WebSocketLink({
    uri: wsUri,
    options: {
      reconnect: true,
      connectionParams: connectionParams
    }
  }),
  new BatchHttpLink({ fetch })
);

// if (__PERSIST_GQL__) {
//   networkInterface = addPersistedQueries(networkInterface, queryMap);
github revskill10 / next-template / modules / core / lib / utils / init-apollo.js View on Github external
)

  const errorLink = onError(
    ({ graphQLErrors, networkError }) => {
      if (graphQLErrors) {
        graphQLErrors.map(err => {
          store.dispatch(openSnackbar({message: err.message, autoHideDuration: 3000}))
        })
      }
      if (networkError) {
        store.dispatch(openSnackbar({message: networkError, autoHideDuration: 3000}))
      }
    }
  )

  let link = ApolloLink.from([errorLink, contextLink, httpLink])

  if (!ssrMode) {

    const wsLink = new WebSocketLink(
      createSubscriptionClient({
        wsUrl: WS_URL,
        store,
        getToken,
      })
    )
    const subscriptionLink = ApolloLink.from([errorLink, wsLink])
        
    // using the ability to split links, you can send data to each link
    // depending on what kind of operation is being sent
    link = split(
      isSubscriptionOperation,
github okgrow / advanced-graphql / web / src / client.js View on Github external
import { BrowserRouter } from 'react-router-dom';
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { ApolloLink } from 'apollo-link';
import { onError } from 'apollo-link-error';
import { HttpLink } from 'apollo-link-http';
import WsLink from 'apollo-link-ws';
import Cache from 'apollo-cache-inmemory';
import App from './components/App';

const errorLink = onError(({ graphqlErrors, networkError }) => {
  // could also be sent to an error logger
  console.error('Apollo Errors caught!', { graphqlErrors, networkError });
});

const authLink = new ApolloLink((operation, forward) => {
  const token = localStorage.getItem('AUTH_TOKEN');

  operation.setContext(() => ({
    headers: {
      authorization: token ? `JWT ${token}` : null,
    },
  }));

  return forward(operation);
});

const hasSubscriptionOperation = operation =>
  operation.query.definitions.reduce(
    (result, definition) => result || definition.operation === 'subscription',
    false
  );
github hasura / custom-resolvers-boilerplate / src / utils.js View on Github external
// Create a WebSocket link:
  const wsLink = new WebSocketLink(new SubscriptionClient(
    uri,
    {
      reconnect: true,
      connectionParams: {
        headers
      }
    },
    ws
  ));

  // chose the link to use based on operation
  const link = split(
    // split based on operation type
    ({ query }) => {
      const { kind, operation } = getMainDefinition(query);
      return kind === 'OperationDefinition' && operation === 'subscription';
    },
    wsLink,
    httpLink,
  );


  return link;
};