Skip to content

Instantly share code, notes, and snippets.

@elitan
Last active March 26, 2019 14:56
Show Gist options
  • Save elitan/9dc45989acc146b1a23231377abaa90c to your computer and use it in GitHub Desktop.
Save elitan/9dc45989acc146b1a23231377abaa90c to your computer and use it in GitHub Desktop.
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 (
<Redirect
to={{
pathname: '/sign-in',
state: { from: this.props.location },
}}
/>
);
}
return (
<ApolloProvider client={this.client}>
{this.props.children}
</ApolloProvider>
);
}
}
export default AuthGate;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment