How to use the apollo-link.from function in apollo-link

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 adrivelasco / graphql-pwa-workshop / client / core / createApolloClient.client.js View on Github external
export default function createApolloClient() {
  // "apollo-link" is a standard interface for modifying control flow of GraphQL requests and fetching GraphQL results,
  // designed to provide a simple GraphQL client that is capable of extensions.
  // https://github.com/apollographql/apollo-link
  const link = from([
    // Handle and inspect errors in your GraphQL network stack.
    // https://github.com/apollographql/apollo-link/tree/master/packages/apollo-link-error
    onError(({ graphQLErrors, networkError }) => {
      if (graphQLErrors) {
        graphQLErrors.map(({ message, locations, path }) =>
          console.warn(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`)
        );
      }
      if (networkError) {
        console.warn(`[Network error]: ${networkError}`);
      }
    }),

    // HTTP Link takes an object with some options on it to customize the behavior of the link.
    // If your server supports it, the HTTP link can also send over metadata about the request in the extensions field.
    // https://github.com/apollographql/apollo-link/tree/master/packages/apollo-link-http
github realm / realm-graphql / src / GraphqlConfig.ts View on Github external
retryIf: async (error) => {
          if (error && error.result && error.result.status === 401) {
            await this.refreshToken(0, /* shouldRetry */ false);
          }

          return true;
        },
      },
    });

    const link = split(({ query }) => {
        const { kind, operation } = getMainDefinition(query);
        return kind === "OperationDefinition" && operation === "subscription";
      },
      subscriptionLink,
      from([retryLink, this.authLink, httpLink]));

    return new ApolloClient({
      link,
      cache,
    });
  }
github Ge-Ge / graphql-demo / src / utils / graphql.js View on Github external
console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
      ),
    );
  if (networkError) console.log(`[Network error]: ${networkError}`);
});

const httpLink = new HttpLink({
  uri: 'https://api.github.com/graphql', // 配置请求url
  headers: {                             // 配置header
    Authorization: `Bearer ${token}`
  }
})
const cache = new InMemoryCache() // 缓存
export default new ApolloClient({
  link: from([Middleware, Afterware, errorLink, httpLink]),
  cache,
  defaultOptions: {
    watchQuery: {
      fetchPolicy: 'cache-and-network',
      errorPolicy: 'ignore',
    },
    query: {
      fetchPolicy: 'network-only',
      errorPolicy: 'all',
    },
    mutate: {
      errorPolicy: 'all'
    }
  }
})
github silverstripe / silverstripe-admin / client / src / boot / apollo / buildClient.js View on Github external
const graphQLConfig = Config.getSection('SilverStripe\\Admin\\LeftAndMain').graphql;
    const cachedTypenames = graphQLConfig && graphQLConfig.cachedTypenames;
    let fragmentData;
    // GraphQL may not return what we want (e.g. if schema is empty, so fail gracefully)
    try {
      fragmentData = await getGraphqlFragments(baseUrl, cachedTypenames);
    } catch (e) {
        fragmentData = null;
    }
    const cache = buildCache(fragmentData);
    const components = buildNetworkComponents(baseUrl);
    const stateLink = withClientState({
      cache,
      resolvers: {}
    });
    const link = from([stateLink, ...components]);
    return new ApolloClient({ cache, link });
};
github apollographql / apollo-client-devtools / src / backend / links.js View on Github external
//
      // The `apollo-link-state` approach uses a custom link chain to parse
      // and execute queries, whereas the Apollo Client local state approach
      // uses Apollo Client directly. To decide which approach to use
      // below, we'll check to see if typeDefs have been set on the
      // ApolloClient instance, as if so, this means Apollo Client local state
      // is being used.

      const supportsApolloClientLocalState =
        typeof apolloClient.typeDefs !== "undefined";

      if (!supportsApolloClientLocalState) {
        // Supports `apollo-link-state`.
        const context = { __devtools_key__: key, cache };

        const devtoolsLink = from([
          errorLink(),
          cacheLink(fetchPolicy),
          schemaLink(),
          userLink,
        ]);

        const operationExecution$ = execute(devtoolsLink, {
          query: queryAst,
          variables,
          operationName,
          context,
        });

        operationExecution$.subscribe(subscriptionHandlers);
        return;
      }
github codeamp / panel / src / lib / apollo.js 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}`)
    }
  });

  return new ApolloClient({
    link: from([
      afterwareLink,
      errorLink,
      middlewareLink,
      httpLink,
    ]),
    cache: new InMemoryCache(),
    defaultOptions: {
      watchQuery: {
        errorPolicy: 'ignore',
        fetchPolicy: 'network-only',
      },
      query: {
        errorPolicy: 'apollo-link',
      },
      mutate: {
        errorPolicy: 'all',
github fusionjs / fusionjs / fusion-plugin-apollo / src / apollo-client / index.js View on Github external
: apolloContext,
            })
          : new HttpLink({
              uri: endpoint,
              credentials: includeCredentials,
              fetch,
            });

      const links: Array = getApolloLinks
        ? getApolloLinks([connectionLink], ctx)
        : [connectionLink];

      const client = new ApolloClient({
        ssrMode: __NODE__,
        connectToDevTools: __BROWSER__ && __DEV__,
        link: apolloLinkFrom(links),
        cache: cache.restore(initialState),
        resolvers,
        typeDefs,
        defaultOptions,
      });
      return client;
    }
    return (ctx: Context, initialState: mixed) => {
github jhen0409 / react-native-debugger / app / worker / apollo / backend / links.js View on Github external
const subscriber = request => {
    const { query, variables, operationName, key, fetchPolicy } = JSON.parse(
      request,
    );
    try {
      const userLink = hook.ApolloClient.link;
      const cache = hook.ApolloClient.cache;

      const devtoolsLink = from([
        errorLink(),
        cacheLink(fetchPolicy),
        schemaLink(),
        userLink,
      ]);
      const obs = execute(devtoolsLink, {
        query: gql(query),
        variables,
        operationName,
        context: { __devtools_key__: key, cache },
      });
      obs.subscribe({
        next: data => bridge.send(`link:next:${key}`, JSON.stringify(data)),
        error: err => bridge.send(`link:error:${key}`, JSON.stringify(err)),
        complete: () => bridge.send(`link:complete:${key}`),
      });