api-client/helpers/apollo.ts

87 lines
1.7 KiB
TypeScript
Raw Normal View History

2021-05-18 09:27:29 +00:00
import {
ApolloClient,
HttpLink,
InMemoryCache,
split,
} from "@apollo/client/core"
import { WebSocketLink } from "@apollo/client/link/ws"
import { setContext } from "@apollo/client/link/context"
import { getMainDefinition } from "@apollo/client/utilities"
2021-06-14 04:07:30 +00:00
import { authIdToken$ } from "./fb/auth"
2021-05-03 13:18:24 +00:00
let authToken: String | null = null
export function registerApolloAuthUpdate() {
2021-06-14 04:07:30 +00:00
authIdToken$.subscribe((token) => {
authToken = token
})
}
2021-05-03 13:18:24 +00:00
/**
* Injects auth token if available
*/
const authLink = setContext((_, { headers }) => {
if (authToken) {
2021-05-03 13:18:24 +00:00
return {
headers: {
...headers,
authorization: `Bearer ${authToken}`,
},
2021-05-03 13:18:24 +00:00
}
} else {
return {
headers,
2021-05-03 13:18:24 +00:00
}
}
})
const httpLink = new HttpLink({
uri:
process.env.CONTEXT === "production"
? "https://api.hoppscotch.io/graphql"
: "https://api.hoppscotch.io/graphql",
2021-05-03 13:18:24 +00:00
})
const wsLink = new WebSocketLink({
uri:
process.env.CONTEXT === "production"
? "wss://api.hoppscotch.io/graphql"
: "wss://api.hoppscotch.io/graphql",
2021-05-03 13:18:24 +00:00
options: {
2021-05-03 13:57:58 +00:00
reconnect: true,
lazy: true,
2021-05-03 13:18:24 +00:00
connectionParams: () => {
2021-05-14 05:50:17 +00:00
return {
authorization: `Bearer ${authToken}`,
2021-05-03 13:18:24 +00:00
}
},
},
})
2021-05-03 13:18:24 +00:00
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query)
2021-05-18 09:27:29 +00:00
return (
definition.kind === "OperationDefinition" &&
definition.operation === "subscription"
)
},
wsLink,
httpLink
)
2021-05-03 13:18:24 +00:00
export const apolloClient = new ApolloClient({
link: authLink.concat(splitLink),
cache: new InMemoryCache(),
defaultOptions: {
query: {
fetchPolicy: "network-only",
errorPolicy: "ignore",
2021-05-03 13:18:24 +00:00
},
watchQuery: {
fetchPolicy: "network-only",
errorPolicy: "ignore",
},
},
})