Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@TariqueNasrullah TariqueNasrullah commented Nov 8, 2020

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

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