apollo.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import {
  2. ApolloClient,
  3. HttpLink,
  4. InMemoryCache,
  5. split,
  6. } from "@apollo/client/core"
  7. import { WebSocketLink } from "@apollo/client/link/ws"
  8. import { setContext } from "@apollo/client/link/context"
  9. import { getMainDefinition } from "@apollo/client/utilities"
  10. import { authIdToken$ } from "./fb/auth"
  11. let authToken: String | null = null
  12. export function registerApolloAuthUpdate() {
  13. authIdToken$.subscribe((token) => {
  14. authToken = token
  15. })
  16. }
  17. /**
  18. * Injects auth token if available
  19. */
  20. const authLink = setContext((_, { headers }) => {
  21. if (authToken) {
  22. return {
  23. headers: {
  24. ...headers,
  25. authorization: `Bearer ${authToken}`,
  26. },
  27. }
  28. } else {
  29. return {
  30. headers,
  31. }
  32. }
  33. })
  34. const httpLink = new HttpLink({
  35. uri:
  36. process.env.CONTEXT === "production"
  37. ? "https://api.hoppscotch.io/graphql"
  38. : "https://api.hoppscotch.io/graphql",
  39. })
  40. const wsLink = new WebSocketLink({
  41. uri:
  42. process.env.CONTEXT === "production"
  43. ? "wss://api.hoppscotch.io/graphql"
  44. : "wss://api.hoppscotch.io/graphql",
  45. options: {
  46. reconnect: true,
  47. lazy: true,
  48. connectionParams: () => {
  49. return {
  50. authorization: `Bearer ${authToken}`,
  51. }
  52. },
  53. },
  54. })
  55. const splitLink = split(
  56. ({ query }) => {
  57. const definition = getMainDefinition(query)
  58. return (
  59. definition.kind === "OperationDefinition" &&
  60. definition.operation === "subscription"
  61. )
  62. },
  63. wsLink,
  64. httpLink
  65. )
  66. export const apolloClient = new ApolloClient({
  67. link: authLink.concat(splitLink),
  68. cache: new InMemoryCache(),
  69. defaultOptions: {
  70. query: {
  71. fetchPolicy: "network-only",
  72. errorPolicy: "ignore",
  73. },
  74. watchQuery: {
  75. fetchPolicy: "network-only",
  76. errorPolicy: "ignore",
  77. },
  78. },
  79. })