import React, { Component } from 'react'; import { Redirect } from 'react-router-dom'; import { ApolloProvider } from 'react-apollo'; import { InMemoryCache } from 'apollo-cache-inmemory'; import ApolloClient from 'apollo-client'; import { setContext } from 'apollo-link-context'; import { WebSocketLink } from 'apollo-link-ws'; import { HttpLink } from 'apollo-link-http'; import { split } from 'apollo-link'; import { getMainDefinition } from 'apollo-utilities'; import { HASURA_GQE_ENDPOINT_WS, HASURA_GQE_ENDPOINT_HTTP, } from '../config'; class AuthGate extends Component { constructor(props) { super(props); const wsurl = `${HASURA_GQE_ENDPOINT_WS}/v1alpha1/graphql`; const httpurl = `${HASURA_GQE_ENDPOINT_HTTP}/v1alpha1/graphql`; const jwt_token = localStorage.getItem('jwt_token'); // create the web socket link const wsLink = new WebSocketLink({ uri: wsurl, options: { reconnect: true, connectionParams: () => ({ headers: { authorization: jwt_token ? `Bearer ${jwt_token}` : '', }, }), }, }); let httpLink = new HttpLink({ uri: httpurl, }); const authLink = setContext((a, { headers }) => { const token = localStorage.getItem('jwt_token'); return { headers: { ...headers, authorization: token ? `Bearer ${token}` : '', }, }; }); const link = split( // split based on operation type ({ query }) => { const { kind, operation } = getMainDefinition(query); return kind === 'OperationDefinition' && operation === 'subscription'; }, wsLink, httpLink ); const client = new ApolloClient({ link: authLink.concat(link), cache: new InMemoryCache(), }); this.client = client; } render() { if (!this.isAuthenticated()) { return ( ); } return ( {this.props.children} ); } } export default AuthGate;