Skip to content

Instantly share code, notes, and snippets.

@KazW
Last active January 29, 2022 14:12
Show Gist options
  • Save KazW/2b5e4cb8f43566a69d3917ee7f30dbcc to your computer and use it in GitHub Desktop.
Save KazW/2b5e4cb8f43566a69d3917ee7f30dbcc 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
}
}
@TariqueNasrullah
Copy link

This saved me from switching to different package. Totally Worked for me.

@silvesterwali
Copy link

hi, thank you for sharing this. can I have the example project to implement this with nuxt-apollo module

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment