@apollo/client#createHttpLink JavaScript Examples

The following examples show how to use @apollo/client#createHttpLink. 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: ApolloClient.js    From nextjs-woocommerce with GNU General Public License v3.0 6 votes vote down vote up
client = new ApolloClient({
  ssrMode: clientSide,
  link: middleware.concat(
    afterware.concat(
      createHttpLink({
        uri: process.env.NEXT_PUBLIC_GRAPHQL_URL,
        fetch,
      })
    )
  ),
  cache: new InMemoryCache(),
})
Example #2
Source File: App.js    From web-frontend with MIT License 5 votes vote down vote up
function App() {
  const [token, setToken] = useState(null);

  const onAuthenticate = (token) => {
    setToken(token);
  };

  if (!token)
    return (
      <div>
        <input id="token" placeholder="github token" />
        <button
          onClick={() => onAuthenticate(document.getElementById("token").value)}
        >
          Authenticate
        </button>
      </div>
    );
  else {
    const httpLink = createHttpLink({
      uri: "https://api.github.com/graphql",
    });

    const authLink = setContext((_, { headers }) => {
      return {
        headers: {
          ...headers,
          authorization: token ? `Bearer ${token}` : "",
        },
      };
    });

    const client = new ApolloClient({
      link: authLink.concat(httpLink),
      cache: new InMemoryCache(),
    });

    return (
      <ApolloProvider client={client}>
        <div className="App">
          <GitHubQuery />
        </div>
      </ApolloProvider>
    );
  }
}
Example #3
Source File: AppEntry.js    From malware-detection-frontend with Apache License 2.0 5 votes vote down vote up
AppEntry = ({ useLogger, connectToDevTools }) => {
    const tags = useRef();
    const registry = useLogger ? init(logger) : init();
    const selectedWorkloads = useRef();
    const selectedSID = useRef();

    const globalFilterLink = setContext((_, { headers }) => ({
        headers: {
            ...headers,
            ...(tags.current?.length && { 'insights-tags': `${tags.current}` }),
            ...(selectedWorkloads.current?.SAP?.isSelected && { 'insights-sap-system': true }),
            ...(selectedWorkloads.current['Ansible Automation Platform']?.isSelected && { 'insights-ansible-system': true }),
            ...(selectedWorkloads.current['Microsoft SQL']?.isSelected && { 'insights-mssql-system': true }),
            ...(selectedSID.current?.length && { 'insights-sap-sids': `${selectedSID.current}` })
        }
    }));
    const client = useMemo(() =>  new ApolloClient({
        link: globalFilterLink.concat(createHttpLink({
            uri: '/api/malware-detection/v1/graphql'
        })),
        cache,
        connectToDevTools
    }, `${tags.current}`), [connectToDevTools, globalFilterLink]);
    registry.register({ notifications });

    useEffect(() => {
        insights.chrome.init();
        insights.chrome.identifyApp('malware');
        if (insights.chrome?.globalFilterScope) {
            insights.chrome.on('GLOBAL_FILTER_UPDATE', ({ data }) => {
                const [workloads, SID, selectedTags] =
                insights.chrome?.mapGlobalFilter?.(data, false, true) || [];
                tags.current =  selectedTags?.join(',') || '';

                selectedWorkloads.current = workloads || {};
                selectedSID.current = SID || [];

                globalFilters({ workloads, SID, selectedTags });

                client.resetStore();
            });
        }

    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [client]);

    return <IntlProvider locale={navigator.language.slice(0, 2)} messages={messages} onError={console.log}>
        <ApolloProvider client={client}>
            <RegistryContext.Provider value={{ getRegistry: () => registry }}>
                <Provider store={registry.getStore()}>
                    <Router basename={getBaseName(window.location.pathname)}>
                        <NotificationsPortal />
                        <App />
                    </Router>
                </Provider>
            </RegistryContext.Provider>
        </ApolloProvider>
    </IntlProvider>;
}
Example #4
Source File: apollo-client.js    From RC4Community with Apache License 2.0 5 votes vote down vote up
httpLink = createHttpLink({
  // Uncomment the appropriate line according to the
  // region group where you created your database.
//   uri: 'https://graphql.fauna.com/graphql',
  // uri: 'https://graphql.eu.fauna.com/graphql',
  uri: 'https://graphql.us.fauna.com/graphql',
})
Example #5
Source File: index.js    From resume-github with MIT License 5 votes vote down vote up
httpLink = createHttpLink({
  uri: 'https://api.github.com/graphql',
})
Example #6
Source File: ApolloWrapper.js    From graphql-sample-apps with Apache License 2.0 5 votes vote down vote up
ApolloWrapper = () => {
  const { isAuthenticated, getIdTokenClaims } = useAuth0();
  const [xAuthToken, setXAuthToken] = useState("");

  useEffect(() => {
    const getToken = async () => {
      const token = isAuthenticated ? await getIdTokenClaims() : "";
      setXAuthToken(token);
    };
    getToken();
  }, [getIdTokenClaims, isAuthenticated]);

  const httpLink = createHttpLink({
    uri: process.env.REACT_APP_BACKEND_ENDPOINT,
  });

  const authLink = setContext((_, { headers, ...rest }) => {
    if (!xAuthToken) return { headers, ...rest };

    return {
      ...rest,
      headers: {
        ...headers,
        "X-Auth-Token": xAuthToken.__raw,
      },
    };
  });

  const wsLink = new WebSocketLink({
    uri: process.env.REACT_APP_BACKEND_ENDPOINT.replace("https://", "wss://"),
    options: {
      reconnect: true,
      minTimeout: 30000,
      connectionParams: {
        "X-Auth-Token": xAuthToken.__raw,
      },
    },
  });

  const splitLink = split(
    ({ query }) => {
      const definition = getMainDefinition(query);
      return (
        definition.kind === "OperationDefinition" &&
        definition.operation === "subscription"
      );
    },
    wsLink,
    authLink.concat(httpLink)
  );

  const client = new ApolloClient({
    cache: new InMemoryCache(),
    link: splitLink,
  });

  return (
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  );
}
Example #7
Source File: server.js    From react-workshop with MIT License 5 votes vote down vote up
server
  .disable('x-powered-by')
  .use(express.static(process.env.RAZZLE_PUBLIC_DIR))
  .get('/*', (req, res) => {
    const apolloClient = new ApolloClient({
      ssrMode: true,
      cache: new InMemoryCache(),
      link: createHttpLink({
        uri: 'https://asia-southeast2-minitokopedia.cloudfunctions.net/graphql',
      }),
    });

    const context = {};
    const markup = (
      <ApolloProvider client={apolloClient}>
        <StaticRouter context={context} location={req.url}>
          <App />
        </StaticRouter>
      </ApolloProvider>
    );

    if (context.url) {
      res.redirect(context.url);
    } else {
      getDataFromTree(markup).then((content) => {
        const initialState = apolloClient.extract();

        const html = renderToString(
          <html lang="en">
            <head>
              <meta httpEquiv="X-UA-Compatible" content="IE=edge" />
              <meta charset="utf-8" />
              <title>Welcome to Razzle</title>
              <meta name="viewport" content="width=device-width, initial-scale=1" />
              {cssLinksFromAssets(razzleAssets, 'client')}
            </head>
            <body>
              <div id="root" dangerouslySetInnerHTML={{ __html: content }} />
              <script
                dangerouslySetInnerHTML={{
                  __html: `window.__APOLLO_STATE__=${JSON.stringify(initialState).replace(/</g, '\\u003c')};`,
                }}
              />
              {jsScriptTagsFromAssets(razzleAssets, 'client')}
            </body>
          </html>,
        );

        res.status(200).header('Content-Type', 'text/html').send(`<!doctype html>\n${html}`);
      });
    }
  });
Example #8
Source File: _app.js    From redis-examples with MIT License 5 votes vote down vote up
link = createHttpLink({
  uri: "https://graphql-us-east-1.upstash.io/",
  headers: {
    Authorization: "Bearer YOUR_READ_ONLY_ACCESS_KEY",
  },
})