@apollo/client#HttpLink JavaScript Examples

The following examples show how to use @apollo/client#HttpLink. 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: client.js    From jamstack-ecommerce with MIT License 6 votes vote down vote up
client = new ApolloClient({
    link: new HttpLink({
        uri: "https://shanstore2.myshopify.com/api/graphql",
        fetch,
        headers: {
            "X-Shopify-Storefront-Access-Token": "a9da41bccc9eb31891047c268e893226"
        }
    }),
    cache: new InMemoryCache()
})
Example #2
Source File: dataProvider.js    From acy-dex-interface with MIT License 6 votes vote down vote up
export function useGraph(querySource, { subgraph = null, subgraphUrl = null, chainName = "arbitrum" } = {}) {
  const query = gql(querySource)

  if (!subgraphUrl) {
    if (!subgraph) {
      subgraph = getChainSubgraph(chainName)
    }
    subgraphUrl = `https://api.thegraph.com/subgraphs/name/${subgraph}`;
  }

  const client = new ApolloClient({
    link: new HttpLink({ uri: subgraphUrl, fetch }),
    cache: new InMemoryCache()
  })
  const [data, setData] = useState()
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)

  useEffect(() => {
    setLoading(true)
  }, [querySource, setLoading])

  useEffect(() => {
    client.query({query}).then(res => {
      setData(res.data)
      setLoading(false)
    }).catch(ex => {
      console.warn('Subgraph request failed error: %s subgraphUrl: %s', ex.message, subgraphUrl)
      setError(ex)
      setLoading(false)
    })
  }, [querySource, setData, setError, setLoading])

  return [data, loading, error]
}
Example #3
Source File: index.js    From graphql-sample-apps with Apache License 2.0 5 votes vote down vote up
httpLink = new HttpLink({
  uri: "http://localhost:8080/graphql",
})
Example #4
Source File: apollo.js    From stacker.news with MIT License 5 votes vote down vote up
additiveLink = from([
  new RetryLink(),
  new HttpLink({ uri: '/api/graphql' })
])
Example #5
Source File: client.js    From jamstack-serverless with MIT License 5 votes vote down vote up
client = new ApolloClient({
  link: new HttpLink({
    uri: '.netlify/functions/graphql_mongodb',
    fetch,
  }),
  cache: new InMemoryCache()
})
Example #6
Source File: client.js    From jamstack-serverless with MIT License 5 votes vote down vote up
client = new ApolloClient({
  link: new HttpLink({
    uri: 'http://localhost:8888/.netlify/functions/graphql_faunadb',
    fetch,
  }),
  cache: new InMemoryCache()
})
Example #7
Source File: client.js    From jamstack-serverless with MIT License 5 votes vote down vote up
client = new ApolloClient({
  link: new HttpLink({
    uri: 'http://localhost:8888/.netlify/functions/graphql_hello',
    fetch,
  }),
  cache: new InMemoryCache()
})
Example #8
Source File: apolloClient.js    From realworld with MIT License 5 votes vote down vote up
function createApolloClient(ctx) {
  const ssrMode = typeof window === 'undefined';

  return new ApolloClient({
    assumeImmutableResults: true,
    connectToDevTools: !ssrMode && process.env.NODE_ENV !== 'production',
    ssrMode,
    name: 'Condit',
    version: '1.0.0',
    link: ApolloLink.from([
      setContext(() => {
        const { authorization } = ssrMode
          ? cookie.parse(ctx?.req?.headers?.cookie ?? '')
          : cookie.parse(document.cookie);
        return {
          headers: { authorization },
        };
      }),
      new HttpLink({
        uri: process.env.NEXT_PUBLIC_GRAPHQL_URL, // Server URL (must be absolute)
        credentials: 'omit', // Additional fetch() options like `credentials` or `headers`
      }),
    ]),
    cache: new InMemoryCache({
      resultCaching: true,
      dataIdFromObject(object) {
        switch (object.__typename) {
          case 'Article':
            return `${object.__typename}:${object.slug}`;
          case 'User':
            return `${object.__typename}:${object.username}`;
          default:
            return defaultDataIdFromObject(object);
        }
      },
      typePolicies: {
        Article: {
          keyFields: ['slug'],
        },
        User: {
          keyFields: ['username'],
        },
        Query: {
          fields: {
            articlesConnection: relayStylePagination(),
            articleBySlug(_, { args, toReference }) {
              return toReference({ __typename: 'Article', slug: args.slug });
            },
            comment(_, { args, toReference }) {
              return toReference({ __typename: 'Comment', id: args.id });
            },
            feedConnection: relayStylePagination(),
            userByUsername(_, { args, toReference }) {
              return toReference({
                __typename: 'User',
                username: args.username,
              });
            },
            tag(_, { args, toReference }) {
              return toReference({ __typename: 'Tag', id: args.id });
            },
          },
        },
      },
    }),
  });
}
Example #9
Source File: auth.js    From grandcast.fm with Apache License 2.0 5 votes vote down vote up
function useProvideAuth() {
  const [authToken, setAuthToken] = useState(null)

  const getAuthHeaders = () => {
    if (!authToken) return null

    return {
      authorization: `Bearer ${authToken}`,
    }
  }

  function createApolloClient() {
    const link = new HttpLink({
      uri: 'http://localhost:4001/graphql',
      headers: getAuthHeaders(),
    })

    return new ApolloClient({
      link,
      cache: new InMemoryCache(),
    })
  }

  const signOut = () => {
    setAuthToken(null)
  }

  const signIn = async ({ username, password }) => {
    const client = createApolloClient()
    const LoginMutation = gql`
      mutation LoginMutation($username: String!, $password: String!) {
        login(username: $username, password: $password) {
          token
        }
      }
    `
    const result = await client.mutate({
      mutation: LoginMutation,
      variables: { username, password },
    })

    console.log(result)

    if (result?.data?.login?.token) {
      setAuthToken(result.data.login.token)
    }
  }

  const isSignedIn = () => {
    if (authToken) {
      return true
    } else {
      return false
    }
  }

  return {
    createApolloClient,
    signIn,
    signOut,
    isSignedIn,
  }
}
Example #10
Source File: seed-db.js    From grandcast.fm with Apache License 2.0 5 votes vote down vote up
client = new ApolloClient({
  link: new HttpLink({ uri, fetch }),
  cache: new InMemoryCache(),
})
Example #11
Source File: ApolloSetup.js    From graphql-sample-apps with Apache License 2.0 5 votes vote down vote up
httpLink = new HttpLink({
    uri: `https://${endpoint}`
})
Example #12
Source File: ApolloProvider.js    From climatescape.org with MIT License 5 votes vote down vote up
ApolloProvider = ({ children }) => {
  const { getTokenSilently, isAuthenticated } = useAuth0()
  const {
    site: { siteMetadata },
  } = useStaticQuery(graphql`
    query ApolloProviderQuery {
      site {
        siteMetadata {
          graphqlUri
        }
      }
    }
  `)

  const tokenLink = setContext(async () => {
    if (!isAuthenticated) return {}

    const token = await getTokenSilently()

    if (!token) return {}

    return {
      headers: { Authorization: `Bearer ${token}` },
    }
  })

  const errorLink = onError(error => {
    console.error("Apollo error", error) // eslint-disable-line no-console
  })

  // TODO: This total hack can be removed once we fix site builds with https
  // for now, the ENV var is insecure by default but we need to secure it
  // for the client in order to prevent "mixed content" errors
  const uri = siteMetadata.graphqlUri.replace("http://", "https://")
  const httpLink = new HttpLink({
    uri,
    fetch,
  })

  const apolloClient = new ApolloClient({
    link: ApolloLink.from([tokenLink, errorLink, httpLink]),
    cache: new InMemoryCache(),
  })

  return (
    <VanillaApolloProvider client={apolloClient}>
      {children}
    </VanillaApolloProvider>
  )
}
Example #13
Source File: link.js    From ReactNativeApolloOnlineStore with MIT License 5 votes vote down vote up
httpLink = new HttpLink({uri: GRAPHQL_URL})
Example #14
Source File: apolloClient.js    From stack-underflow with MIT License 5 votes vote down vote up
httpLink = new HttpLink({
  uri: backendUrl,
})
Example #15
Source File: App.jsx    From Consuming-GraphqL-Apollo with MIT License 5 votes vote down vote up
client = new ApolloClient({
  cache: new InMemoryCache(),
  link: new HttpLink({
    uri: "http://localhost:4000/graphql" // your graphql server link
  }),
  credentials: "same-origin",
})
Example #16
Source File: client.js    From gatsby-apollo-wpgraphql-jwt-starter with MIT License 5 votes vote down vote up
httpLink = new HttpLink(
  {
    uri: process.env.GRAPHQL_URL,
    fetch,
    // credentials: 'include',
  }
)
Example #17
Source File: apolloClient.js    From web-frontend with MIT License 5 votes vote down vote up
client = new ApolloClient({
  cache: new InMemoryCache(),
  link: new HttpLink({
    uri: 'https://graphbrainz.herokuapp.com/',
  })
})
Example #18
Source File: App.js    From web-frontend with MIT License 5 votes vote down vote up
httpLink = new HttpLink({
  uri: "https://rickandmortyapi.com/graphql",
})