Skip to content

Instantly share code, notes, and snippets.

@TariqueNasrullah
Forked from KazW/apollo-config.js
Created November 8, 2020 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TariqueNasrullah/382c18205de33b2b961484615c23fdcc to your computer and use it in GitHub Desktop.
Save TariqueNasrullah/382c18205de33b2b961484615c23fdcc to your computer and use it in GitHub Desktop.
Hasura, Nuxt (Vue), Nuxt Auth, Auth0 and Apollo
import { SubscriptionClient } from 'subscriptions-transport-ws'
import { onError } from 'apollo-link-error'
import { setContext } from 'apollo-link-context'
import { split, from } from 'apollo-link'
import { WebSocketLink } from 'apollo-link-ws'
import { getMainDefinition } from 'apollo-utilities'
import { createUploadLink } from 'apollo-upload-client'
import * as ws from 'ws'
export default (context) => {
let link
const baseUrl = context.env.graphBaseUrl
const logOut = async function () {
await context.$auth.logout()
await context.$apolloHelpers.onLogout()
if (process.server) context.redirect('/')
}
const errorLink = onError(
async ({ graphQLErrors, networkError, operation, forward }) => {
const target = 'JWTExpired'
if (
(networkError && networkError.message.includes(target)) ||
(graphQLErrors && graphQLErrors[0].message.includes(target))
)
await logOut()
return forward(operation)
}
)
const httpLink = createUploadLink({
uri: `https://${baseUrl}`
})
link = from([errorLink, httpLink])
const authLink = setContext(async (_, { headers }) => {
const Authorization = await context.$auth.getToken('auth0')
const authorizationHeader = Authorization ? { Authorization } : {}
return {
headers: {
...headers,
...authorizationHeader
}
}
})
link = authLink.concat(link)
const connectionCallback = async function (err) {
if (typeof err === 'string' && err.includes('JWTExpired')) await logOut()
}
const wsClient = new SubscriptionClient(
`wss://${baseUrl}`,
{
reconnect: true,
lazy: true,
timeout: 10000,
minTimeout: 1000,
inactivityTimeout: 60000,
connectionCallback,
connectionParams: async () => {
const Authorization = await context.$auth.getToken('auth0')
return Authorization
? { Authorization, headers: { Authorization } }
: {}
}
},
process.server ? ws : WebSocket
)
const wsLink = new WebSocketLink(wsClient)
if (process.server) {
link = split(
({ query }) => {
const { kind, operation } = getMainDefinition(query)
return kind === 'OperationDefinition' && operation === 'subscription'
},
wsLink,
link
)
} else {
link = from([errorLink, wsLink])
}
return {
defaultHttpLink: false,
link
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment