Cloud Defense Logo

Products

Solutions

Company

Book A Live Demo

Top 10 Examples of "apollo-link in functional component" in JavaScript

Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'apollo-link' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.

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();
  });
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 };
        },
      };
    });
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);
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) {
}
  }
});

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);
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 });
}
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);
)

  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,
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
  );
// 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;
};

Is your System Free of Underlying Vulnerabilities?
Find Out Now