Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2020
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. import { InMemoryCache } from 'apollo-cache-inmemory';
  2. import ApolloClient from 'apollo-client';
  3. import { setContext } from 'apollo-link-context';
  4. import { WebSocketLink } from 'apollo-link-ws';
  5. import { HttpLink } from 'apollo-link-http';
  6. import { split } from 'apollo-link';
  7. import { getMainDefinition } from 'apollo-utilities';
  8. import { auth } from '../nhost';
  9.  
  10. import { HASURA_GQE_ENDPOINT_WS, HASURA_GQE_ENDPOINT_HTTP } from '../config';
  11.  
  12. export const generateApolloProviderClient = (param_headers = {}) => {
  13.  
  14. const wsurl = HASURA_GQE_ENDPOINT_WS;
  15. const httpurl = HASURA_GQE_ENDPOINT_HTTP;
  16.  
  17. // create the web socket link
  18. const wsLink = new WebSocketLink({
  19. uri: wsurl,
  20. options: {
  21. reconnect: true,
  22. connectionParams: () => {
  23.  
  24. const jwt_token = auth.getJWTToken();
  25.  
  26. if (!jwt_token) {
  27. return {
  28. headers: {
  29. ...param_headers,
  30. },
  31. }
  32. }
  33.  
  34. return {
  35. headers: {
  36. authorization: `Bearer ${jwt_token}`,
  37. ...param_headers,
  38. },
  39. };
  40. },
  41. },
  42. });
  43.  
  44. let httpLink = new HttpLink({
  45. uri: httpurl,
  46. });
  47.  
  48. const authLink = setContext((a, { headers }) => {
  49. const jwt_token = auth.getJWTToken();
  50. return {
  51. headers: {
  52. ...headers,
  53. authorization: jwt_token ? `Bearer ${jwt_token}` : '',
  54. ...param_headers,
  55. },
  56. };
  57. });
  58.  
  59. const link = split(
  60. // split based on operation type
  61. ({ query }) => {
  62. const { kind, operation } = getMainDefinition(query);
  63. return kind === 'OperationDefinition' && operation === 'subscription';
  64. },
  65. wsLink,
  66. httpLink
  67. );
  68.  
  69. return new ApolloClient({
  70. link: authLink.concat(link),
  71. cache: new InMemoryCache(),
  72. });
  73. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement