How to use apollo-link-batch-http - 10 common examples

To help you get started, we’ve selected a few apollo-link-batch-http 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 mtmendonca / ace-boilerplate / app / src / App.js View on Github external
UNSAFE_componentWillMount() {
    const { protocol, host } = location;
    const wsProtocol = protocol.includes('https') ? 'wss:' : 'ws:';

    try {
      const [, JWT] = (location.search || 'jwt=')
        .match(/jwt=((?!&).)*/gi)[0]
        .split('=');
      localStorage.setItem('token', JWT);
      const httpLink = ApolloLink.from([
        AuthLink,
        new BatchHttpLink({ uri: `${protocol}//${host}/graphql` }),
      ]);
      const wsLink = new WebSocketLink({
        uri: `${wsProtocol}//${host}/subscriptions`,
        options: {
          reconnect: true,
          connectionParams: { JWT },
        },
      });
      const link = split(
        // split based on operation type
        ({ query }) => {
          const { kind, operation } = getMainDefinition(query);
          return kind === 'OperationDefinition' && operation === 'subscription';
        },
        wsLink,
        httpLink,
github cdmbase / fullstack-pro / servers / frontend-server / src / config / apollo-client.ts View on Github external
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 });
}

const links = [errorLink, ...modules.link, /** ...modules.errorLink, */ link];

// Add apollo logger during development only
if ((process.env.NODE_ENV === 'development' || __DEBUGGING__) && __CLIENT__) {
    links.unshift(apolloLogger);
}

let _apolloClient: ApolloClient;
const createApolloClient = () => {
    if (_apolloClient) {
        // return quickly if client is already created.
        return _apolloClient;
    }
    const params: ApolloClientOptions = {
github sysgears / apollo-universal-starter-kit / modules / core / common / createApolloClient.ts View on Github external
}
      }
    ),
    {
      reset: () => {
        // On apolloClient.resetStore() reset only netCache and keep localCache intact
        return netCache.reset();
      }
    }
  );

  const getApolloClient = (): ApolloClient => client;

  const queryLink = createNetLink
    ? createNetLink(apiUrl, getApolloClient)
    : new BatchHttpLink({
        uri: apiUrl,
        credentials: 'include',
        fetch
      });

  let apiLink = queryLink;
  if (apiUrl && (__TEST__ || typeof navigator !== 'undefined')) {
    const finalConnectionParams = {};
    if (connectionParams) {
      for (const connectionParam of connectionParams) {
        Object.assign(finalConnectionParams, (connectionParam as any)());
      }
    }

    const wsUri = apiUrl.replace(/^http/, 'ws');
github sysgears / apollo-universal-starter-kit / modules / core / common / createApolloClient.ts View on Github external
}
      }
    ),
    {
      reset: () => {
        // On apolloClient.resetStore() reset only netCache and keep localCache intact
        return netCache.reset();
      }
    }
  );

  const getApolloClient = (): ApolloClient => client;

  const queryLink = createNetLink
    ? createNetLink(apiUrl, getApolloClient)
    : new BatchHttpLink({
        uri: apiUrl,
        credentials: 'include',
        fetch
      });

  let apiLink = queryLink;
  if (apiUrl && (__TEST__ || typeof navigator !== 'undefined')) {
    const finalConnectionParams = {};
    if (connectionParams) {
      for (const connectionParam of connectionParams) {
        Object.assign(finalConnectionParams, (connectionParam as any)());
      }
    }

    const wsUri = apiUrl.replace(/^http/, 'ws');
github luniehq / lunie / src / gql / apollo.js View on Github external
const makeHttpLink = urlParams => {
  const host = graphqlHost(urlParams)
  const uri = host

  // We create a createPersistedQueryLink to lower network usage.
  // With this, a prefetch is done using a hash of the query.
  // if the server recognises the hash, it will reply with the full response.
  return createPersistedQueryLink().concat(
    new BatchHttpLink({
      uri
    }),
    new RetryLink()
  )
}
github Sitecore / jss / samples / vue / src / lib / GraphQLClientFactory.js View on Github external
export default function(endpoint, ssr, initialCacheState) {
  /* HTTP link selection: default to batched + APQ */
  const link = createPersistedQueryLink().concat(
    new BatchHttpLink({ uri: endpoint, credentials: 'include' })
  );
  // basic HTTP link
  // const link = createHttpLink({ uri: endpoint, credentials: 'include' });

  const cache = new InMemoryCache({
    fragmentMatcher: new IntrospectionFragmentMatcher({
      introspectionQueryResultData,
    }),
  });

  return new ApolloClient({
    ssrMode: ssr,
    ssrForceFetchDelay: 100,
    link,
    cache: cache.restore(initialCacheState),
  });
github Sitecore / jss / samples / basic-sample-react-graphql / lib / GraphQL / BasicGraphQLClientFactory.js View on Github external
export default function(endpoint, ssr, initialCacheState) {
  /* HTTP link selection: default to batched + APQ */
  const link = createPersistedQueryLink().concat(
    new BatchHttpLink({ uri: endpoint, credentials: 'include' })
  );

  const cache = new InMemoryCache({
    fragmentMatcher: new IntrospectionFragmentMatcher({
      introspectionQueryResultData,
    }),
  });

  return new ApolloClient({
    ssrMode: ssr,
    ssrForceFetchDelay: 100,
    link,
    cache: cache.restore(initialCacheState),
  });
}
github Sitecore / jss / samples / basic-sample-react-graphql / lib / GraphQL / SubscriptionGraphQLClientFactory.js View on Github external
export default function(endpoint, ssr, initialCacheState) {
  /*
    QUERY LINK SELECTION
    A link is transport which GraphQL queries are pushed across.
    You have many choices; see BasicGraphQLClientFactory for more details
  */

  // Generally speaking this APQ + batching link is the right choice for most cases.
  const automaticPersistHttp = createPersistedQueryLink().concat(
    new BatchHttpLink({ uri: endpoint, credentials: 'include' })
  );

  /* HTTP link selection */
  let link = automaticPersistHttp;

  /*
    SUBSCRIPTIONS LINK
    Subscriptions are real-time data; they run over WebSockets.
    When server-side rendering, we do not want to enable subscriptions so we don't link them;
    enabling them (e.g. with `ws`) will cause Node to hang during SSR.
    For SSR set 'ssr: false' in your query options for subscription queries.
  */
  if (!ssr) {
    // The endpoint for Sitecore is the same as the HTTP(s) endpoint, but with ws:// or wss:// (encrypted)
    const subscriptionsEndpointUrl = endpoint.replace(/^http(s?)/, 'ws$1');
github HSLdevcom / jore-map-ui / src / util / ApolloClient.ts View on Github external
constructor() {
        this.client = new Apollo.ApolloClient({
            cache,
            link: new BatchHttpLink({
                uri: `${constants.API_URL}/graphql`,
                // To keep the same express session information with each request
                credentials: 'include'
            })
        });
    }
github cofacts / rumors-site / lib / apollo.js View on Github external
/**
 * Maps GraphQL object
 * @param {object} object
 */
function customIdMapper(object) {
  switch (object.__typename) {
    case 'ArticleReply':
      return `${object.__typename}:${object.articleId}__${object.replyId}`;
    default:
      // fall back to default handling
      return defaultDataIdFromObject(object);
  }
}

const config = {
  link: new BatchHttpLink({
    uri: `${PUBLIC_API_URL}/graphql`, // Server URL (must be absolute)
    headers,
    credentials: 'include', // Additional fetch() options like `credentials` or `headers`
  }),
  createCache() {
    return new InMemoryCache({ dataIdFromObject: customIdMapper });
  },
};

export default withData(config);

apollo-link-batch-http

Batch HTTP transport layer for GraphQL

MIT
Latest version published 4 years ago

Package Health Score

56 / 100
Full package analysis

Popular apollo-link-batch-http functions

Similar packages