-
-
Save foxted/c10b84a132b07f69a4d74a45ca11675b to your computer and use it in GitHub Desktop.
Hasura, Nuxt (Vue), Nuxt Auth, Auth0 and Apollo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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